我有两个数据库表:" blog_posts"和" blog_comments"。
blog_posts:
postID | postTitle | postContent | ...
1 | Hello World | This is a blog post | ...
2 | Lorem Ipsum | This is another blog post | ...
3 | Test Post | This is a third post | ...
blog_comments:
commentID | postID | comment | ...
1 | 1 | Very cool | ...
2 | 1 | Nice | ..
我当前的SQL查询是:
SELECT
blog_posts.*,
COUNT(blog_comments.commentID) AS commentCount
FROM
blog_posts
LEFT JOIN blog_comments ON blog_posts.postID = blog_comments.post_id;
如果此帖子没有评论,我希望它返回0作为commentCount,但是查询只返回第一个帖子,这是目前唯一有评论的帖子。
我该如何解决?
感谢。
答案 0 :(得分:0)
您正在使用COUNT
而没有指定分组列,这意味着所有行都会聚合为一个,并在整个集合上计算计数。
明确指定分组列,您应该没问题:
SELECT
blog_posts.*,
COUNT(blog_comments.commentID) AS commentCount
FROM
blog_posts
LEFT JOIN blog_comments ON blog_posts.postID = blog_comments.post_id
GROUP BY blog_posts.postID;