gpt4 book ai didi

php - SQL 子查询返回更多行和更多列

转载 作者:行者123 更新时间:2023-11-29 19:29:21 24 4
gpt4 key购买 nike

实际中如何解决nested responds to comments ?我有一个包含列的表格:

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

第一个解决方案(非常低效)

// 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 = ?

关于php - SQL 子查询返回更多行和更多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41911586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com