php – 从两个表中选择而不重复所有值

让我自己澄清一下,我的问题是“如何从绑定单个表和交叉引用表中选择行而不重复值?”

现在我有三个表,一个交叉引用表和两个单表:

           Table jobs
╔══════════╦══════════════════════════╗
║ job_id   ║  details                 ║
╠══════════╬══════════════════════════╣
║  1       ║  Looking for hire...     ║
║  2       ║  We need help!...        ║
║  3       ║  We are a store that...  ║
║  4       ║  Help wanted...          ║
╚══════════╩══════════════════════════╝

      Table job2pos
╔═══════════╦═════════════╗
║  job_id   ║ position_id ║
╠═══════════╬═════════════╣
║  1        ║  10         ║
║  2        ║  10         ║
║  2        ║  12         ║
║  3        ║  11         ║
║  3        ║  13         ║
║  4        ║  10         ║
╚═══════════╩═════════════╝

        Table positions
╔═══════════════╦═══════════════╗
║ position_id   ║ position_name ║
╠═══════════════╬═══════════════╣
║  10           ║  waitress     ║
║  11           ║  cashier      ║
║  12           ║  cook         ║
║  13           ║  chef         ║
╚═══════════════╩═══════════════╝

当我执行此查询时:

$sql = "SELECT jobs.details, positions.name AS position FROM jobs
INNER JOIN job2pos ON jobs.job_id = job2pos.job_id
INNER JOIN positions ON job2pos.position_id = positions.position_id
WHERE job2pos.job_id IN (2)";
...
print_r($stmt->fetchAll(\PDO::FETCH_ASSOC));

我得到以下内容:

Array(
  [0] => Array ([details] => We need help!...
                [position] => Waitress)
  [1] => Array ([details] => We need help!...
                [position] => Cook)
)

现在我为同一份工作获得了2行,但我想要的是类似于此的东西:

Array(
  [0] => Array ([details] => We need help!...
                [position] => Array ([0] => Waitress
                                     [1] => Cook)
               )
)

>如果你能指出我的代码中有一些不必要的代码,那就太好了.

最佳答案 您只能使用一个sql语句来描述所描述的内容.你可以把结果想象成一张桌子.您不能在普通的SQL中拥有任何嵌套信息.

我们可以选择nosql数据库来存储和检索对象.

但是,我认为你真正想要的是选择multiple statements with one call.

mysqli documentation

MySQL optionally allows having multiple statements in one statement
string. Sending multiple statements at once reduces client-server
round trips but requires special handling.

Multiple statements or multi queries must be executed with
07003. The individual statements of the statement
string are separated by semicolon. Then, all result sets returned by
the executed statements must be fetched.

The MySQL server allows having statements that do return result sets
and statements that do not return result sets in one multiple
statement.

对于this Q&A的PDO:

$stmt   = $db->query("SELECT 1; SELECT 2;");
$stmt->nextRowset(); //Move to next statement result
var_dump( $stmt->fetchAll(PDO::FETCH_ASSOC) ); //SELCT 2 result
点赞