2017-01-28 180 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 = ?