我有以下表格:
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/