0

我有以下表格:

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 条的帖子?

4

1 回答 1

0
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每个帖子的所有 s 和评论数。然后,您将其连接到帖子表使用LEFT JOIN,以便您的结果包括没有评论的帖子。

于 2013-06-05T19:24:27.250 回答