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']]);
}
第二の溶液(動作しない)あなたは1列のみと上記の方法を使用して、最大で1行を選択することができますので、
$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]);
リレーショナルDBに参加左自己を使用することができます2番目(リレーショナル)な方法で、あなたはjoinでそれを行うことができます。 – scaisEdge