[英]MySQL join not returning the rows when trying to count from left table
我有 2 个表格、文章和 article_comments。 试图获取文章列表页面上的评论计数。 但是,我的查询不会返回任何没有任何评论的文章。
SELECT `articles`.*, COUNT(comments.id) AS comment_count
FROM `articles` as `articles`
LEFT JOIN `article_comments` as `comments` ON `articles`.`id` = `comments`.`article_id`
如果该帖子没有评论,如何使查询返回评论计数为0的文章中的所有行?
显然,您的查询缺少GROUP BY
子句,该子句应该枚举articles
表中的所有列 - 或者,如果您正在运行 MySQL 并禁用 sql 模式ONLY_FULL_GROUP_BY
,它应该包含articles
的主键。
使用相关子查询来表达这一点可能更简单:
select
a.*,
coalesce(
(select count(*) from article_comments ac where ac.article_id = a.id),
0
) comments_count
from articles a
您还可以在子查询中预先聚合:
select
a.*,
coalesce(c.comments_count, 0) comments_count
from articles a
left join (
select article_id, count(*) comments_count
from article_comments
group by article_id
) c on c.article_id = a.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.