关于关联查询的sql查询不全的问题

就是两个表,一个是文章表:attop_article,一个是分类表:attop_article_type。

文章表:attop_article_type
图片描述

分类表:attop_article_type
图片描述

关联的是attop_article表中的type与attop_article_type表中的id。希望统计分类下面所有的文章数量是多少。
目前所用的sql是:

SELECT attop_article_type.id,COUNT(attop_article.type)FROM attop_article_type LEFT JOIN attop_article ON attop_article_type.id=attop_article.type GROUP BY attop_article.type ORDER BY attop_article_type.id;

但是效果并不好,未能统计全,我希望没有文章的能默认填零,而这段只能做到没有文章的忽略。

sql执行效果:
图片描述

希望能一次性执行,id能全部查询出来,并能统计所属id的文章数量。感谢。

阅读 2.6k
3 个回答
select id,title,(select count(*) from attop_article where attop_article.type = attop_article_type.id) as count from attop_article_type;

GROUP BY attop_article.type ==》GROUP BY attop_article_type.id

SELECT attop_article_type.id,COUNT(attop_article.type)FROM attop_article_type LEFT JOIN attop_article ON attop_article_type.id=attop_article.type GROUP BY attop_article_type.id ORDER BY attop_article_type.id;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题