SQL子查询返回包含更多列的更多行

时间:2017-01-28 15:37:59

标签: php mysql subquery

如何在实践中解决nested responds to comments?我有一个列表:

  • comment_id int ,评论的主键)
  • 作者 varchar ,发件人姓名)
  • 内容文字,消息内容)
  • book_id int ,另一个表的外键)
  • response_to int ,可以 NULL ,此表的外键)

我需要SQL查询中的这样的数组:

$result = [
  [ // First comment
     'author' => 'Michael',
     'content' => 'It's very good book!',
     'responds' => [
         ['author' => 'Martin', 'content' => 'I agree.'],
         ['author' => 'Susan', 'content' => 'Hello world!.']
     ]
  ],
  [ // Another comment
     'author' => 'Tomas',
     'content' => 'Hi everyone!',
     'responds' => [
         ['author' => 'Jane', 'content' => 'Hi.']
     ]
  ],
  ...
];

第一种解决方案(非常缺乏)

// Get all the comments of this book.
$comments = $db->query('SELECT * FROM comments WHERE book_id = ? AND response_to IS NULL', [$bookId]);

// Find all the responds to each comments. 
foreach ($comments as &$comment) {
    $comment['responds'] = $db->query('SELECT * FROM comments WHERE response_to = ?', [$comment['comment_id']]);
}

第二种解决方案(不工作)

$db->query('SELECT t1.*,
  (SELECT * FROM comments AS t2 WHERE t2.response_to = t1.comment_id) AS responds
  FROM comments AS t1 WHERE t1.book_id = ?', [$bookId]);

1 个答案:

答案 0 :(得分:0)

错误是因为您只能使用上述方法选择一列,最多一行。

您可以使用左自联接

select *
from comments t1
left join comments t2
on t1.comment_id = t2.response_to
where t1.book_id = ?