2017-01-28 147 views
0

更多的行如何在实践中nested responds to comments解决?我有列的表格:SQL子查询返回与多个列

  • COMMENT_IDINT,评论的主键)
  • 作者VARCHAR,发件人的名字)
  • 内容文本消息的,内容)
  • book_idINT,外键到另一个表)
  • response_toINT,可以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.'] 
    ] 
    ], 
    ... 
]; 

第一溶液(非常ineficient)

// 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]); 
+0

关系数据库不返回嵌套表..但表之间的关系。(别名由所选列组成行的选择)..如果你需要这个第二(关系)的方式,你可以通过加入 – scaisEdge

回答

0

错误是因为你只能选择一列,用上面的方法最多一行。

您可以使用左自联接,而不是

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