0
更多的行如何在實踐中nested responds to comments解決?我有列的表格:SQL子查詢返回與多個列
- 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.']
]
],
...
];
第一溶液(非常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]);
關係數據庫不返回嵌套表..但表之間的關係。(別名由所選列組成行的選擇)..如果你需要這個第二(關係)的方式,你可以通過加入 – scaisEdge