简体   繁体   中英

SQL subquery returns more rows with more columns

how to solve in practice nested responds to comments ? I have a table with columns:

  • comment_id ( int , primary key of comment)
  • author ( varchar , name of sender)
  • content ( text , content of message)
  • book_id ( int , foreign key to another table)
  • response_to ( int , can be NULL , foreign key to this table)

and I would need such array from the SQL query:

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

First solution (very 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']]);
}

Second solution (not working)

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

Error is because you can only select one column and at most one row using the above method.

You can use left self join instead

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM