Php MySQL join在尝试从左表计数时不返回行
我有两个表格、文章和文章注释。正在尝试获取文章列表页面上的评论计数。但是,我的查询不会返回任何没有任何注释的文章Php MySQL join在尝试从左表计数时不返回行,php,mysql,sql,join,group-by,Php,Mysql,Sql,Join,Group By,我有两个表格、文章和文章注释。正在尝试获取文章列表页面上的评论计数。但是,我的查询不会返回任何没有任何注释的文章 SELECT `articles`.*, COUNT(comments.id) AS comment_count FROM `articles` as `articles` LEFT JOIN `article_comments` as `comments` ON `articles`.`id` = `comments`.`article_id` 如果没有对该帖子的评论,我如何
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
子句,该子句应枚举文章表中的所有列-或者,如果您在sql模式下运行MySQL,并且禁用了ONLY\u FULL\u GROUP\u 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
您还可以在子查询中预聚合:
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
如前所述,该查询应该满足您的要求(尽管对于任何没有注释的文章,它会将NULL
作为comment\u count
;您可以将其转换为0
,使用COALESCE
)。您是否没有向我们显示WHERE
子句?我在您的查询中没有看到GROUP BY子句。必须使用函数的窗口变量:选择'articles`.*,COUNT(comments.id)OVER()作为comment\u COUNT…
@Nick没有where子句。问题是它没有返回没有评论的文章。请通过编辑澄清,而不是评论。但是,这是一个常见问题。(显然)在考虑发帖之前,请阅读本手册,谷歌搜索任何错误信息,或您的问题/问题/目标的许多清晰、简洁和准确的措辞,有或没有您的特定字符串/名称和网站:stackoverflow.com&tags;阅读许多答案。如果你发布一个问题,用一句话作为标题。反思你的研究。请在代码问题中给出一个--cut&paste&runnable代码,包括作为代码输入的最小代表性示例;期望和实际输出(包括逐字记录错误消息);标签和版本;清晰的说明和解释。给出你能给出的最少代码,即你显示的代码是OK的,扩展为你显示的代码是不OK的。(调试基础。)用于包含DBMS和DDL(包括约束和索引)的SQL,并将其作为格式化为表的代码输入。