簡體   English   中英

SQL子查詢返回更多行和更多列

[英]SQL subquery returns more rows with more columns

在實踐中如何解決嵌套響應評論 我有一個帶有列的表:

  • 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.']
     ]
  ],
  ...
];

第一個解決方案(效率很低)

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

錯誤是因為使用上述方法只能選擇一列,最多只能選擇一行。

您可以使用左自連接

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM