php - 关于关联查询的sql查询不全的问题
黄舟
黄舟 2017-04-11 10:09:48
[PHP讨论组]

就是两个表,一个是文章表: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的文章数量。感谢。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(3)
巴扎黑
select id,title,(select count(*) from attop_article where attop_article.type = attop_article_type.id) as count from attop_article_type;
PHP中文网

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;
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号