gpt4 book ai didi

mysql - 从表中选择行,其中连接的表具有超过 X 个条目

转载 作者:行者123 更新时间:2023-11-30 01:35:30 25 4
gpt4 key购买 nike

我有以下表格:

posts
post_id | user_id | text
1 | 12 | blabla
2 | 64 | sususus

comments
comment_id | post_id | user_id | text
1 | 1 | 55 | I like this...
2 | 2 | 66 | Yeah, me also!
...

现在帖子和评论通过 post_id id 连接。如何获取所有少于 18 条评论的帖子?

最佳答案

SELECT p.* 
FROM posts p
LEFT JOIN (
SELECT post_id, COUNT(*) AS total
FROM comments
GROUP BY post_id
) p2
ON p.post_id = p2.post_id
WHERE p2.total < 18 OR p2.total IS NULL

此处,您使用子查询来获取所有 post_id 以及每个帖子的评论数。然后,您使用LEFT JOIN将其连接到帖子表,以便您的结果包含没有评论的帖子。

关于mysql - 从表中选择行,其中连接的表具有超过 X 个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16948035/

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