mysql按条件统计count,及关联查询显示count为0的记录问题
发表于:2021-12-24 09:43:51浏览:4518次
业务场景是这样的。我在关联查询时,需要按不同的条件,统计出两个或者多个count。并且也要显示出count为0的记录。
拆分问题:
1、按条件统计多个count
2、使用count后关联查询失效。count为0的记录不显示。
解决方法如下:
1、按条件统计count可以用如下方法
COUNT(IF(条件 , 统计字段, NULL))
SELECT t1.*,COUNT(IF(t3.status = 1 , t2.id, NULL)) AS downCount,COUNT(IF(t3.status = 2 , t2.id, NULL)) AS upCount FROM ex_exam_question t1 LEFT JOIN ex_exam_question_suggestion t2 ON t2.question_id = t1.`id` LEFT JOIN ex_exam_question_suggestion_item t3 ON t2.suggestion_item_id = t3.id WHERE 1=1
2、解决关联查询失效问题
通过加group by来解决
将上述sql修改如下
SELECT t1.*,COUNT(IF(t3.status = 1 , t2.id, NULL)) AS downCount,COUNT(IF(t3.status = 2 , t2.id, NULL)) AS upCount FROM ex_exam_question t1 LEFT JOIN ex_exam_question_suggestion t2 ON t2.question_id = t1.`id` LEFT JOIN ex_exam_question_suggestion_item t3 ON t2.suggestion_item_id = t3.id WHERE 1=1 GROUP BY t1.`id`
栏目分类全部>
推荐文章
- ubuntu20.04更换阿里源
- Linux 下安装python3
- GitHub加载缓慢无法访问 使用GitHubFast加快访问
- TP6便捷快速查询日、月、年数据的方法
- mysql 更新json数据中文防止被转义
- 解决 Github 打不开或打开很慢的问题
- windows cmd “Loaded Configuration File none”未加载php.ini的解决办法
- PHP判断网站的访问来源是否是蜘蛛
- 解决composer install遇到:Your requirements could not be resolved to an installable set of packages
- mysql5.7*分组排序 取最新的一条
