基本上我想选择至少有一条评论的所有帖子,并获取每条评论的评论数。到目前为止我所提到的只是给了我一个结果,这是一个准确的计数,但有不止一个帖子有评论。任何建议的更改都可以使这项工作
SELECT
posts.id,
COUNT(DISTINCT comments.post_id) AS count
FROM
posts
LEFT JOIN comments ON posts.id = comments.post_id
答案 0 :(得分:2)
使用汇总功能,您必须将它们分组see here GROUP BY (Aggregate) Functions,这些帖子必须包含至少一个您可以使用的评论HAVING count >= 1
SELECT
posts.id,
COUNT(DISTINCT comments.post_id) AS `count`
FROM
posts
LEFT JOIN comments ON posts.id = comments.post_id
GROUP BY posts.id
HAVING `count` >= 1
答案 1 :(得分:1)
您需要group by
声明。您可以将join
更改为内部联接,因为您只需要包含评论的帖子:
SELECT p.id, COUNT(*) AS count
FROM posts p INNER JOIN
comments c
ON p.id = c.post_id
GROUP BY p.id;
表达式count(distinct c.post_id)
将为每一行返回1
,因为每行只有一个不同的帖子ID。 COUNT(*)
将获得评论数量。