MySQL 联接和 COUNT() 未返回所有记录
MySQL Joins and COUNT() not returning all records
我有两个数据库表:"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;
如果没有对此 post 的评论,我希望它 return 0 作为 commentCount,但查询 return 仅是第一个 post目前唯一有评论的。
我该如何解决?
谢谢。
您使用的 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;
我有两个数据库表:"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;
如果没有对此 post 的评论,我希望它 return 0 作为 commentCount,但查询 return 仅是第一个 post目前唯一有评论的。
我该如何解决?
谢谢。
您使用的 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;