2017-01-28 3 views
0

実際に解決する方法nested responds to commentsSQLサブクエリは、列が多い行を返します

  • 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']]); 
} 

第二の溶液(動作しない)あなたは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]); 
+0

リレーショナルDBに参加左自己を使用することができます2番目(リレーショナル)な方法で、あなたはjoinでそれを行うことができます。 – scaisEdge

答えて

0

エラーがあります。

あなたは、あなたがこれを必要とする場合..ネストした表を戻しますが、テーブル間の関係...(選択された列で構成行の選択エイリアス)していない代わりに

select * 
from comments t1 
left join comments t2 
on t1.comment_id = t2.response_to 
where t1.book_id = ? 
関連する問題