今天在项目过程中报错:
### SQL: SELECT UNIT_NAME,dc.CAPTION as area,ifnull(a.bgSum,0) AS bgSum,ifnull(concat(FORMAT(a.bgSum/k.m*100,1),'%'),'0.0%') as bgRatio FROM inspection_station_info isi left join dic_content dc on dc.CODE_VALUE = isi.COUNTRY_CODE LEFT JOIN (SELECT COUNT(*) as m FROM warning_result) k ON 1=1 LEFT JOIN ( select ifnull(count(distinct wr.BGBH),0) as bgSum,isi.UNIT_ID unitId FROM inspection_station_info isi LEFT JOIN warning_result wr ON isi.UNIT_ID=wr.UNIT_ID left join dic_content dc on dc.CODE_VALUE = isi.COUNTRY_CODE WHERE dc.CODE_VALUE like '3205%' and wr.CHECK_METHOD = ? and year(CHECK_DATE) = ? and month(CHECK_DATE) = ? group by unitId order by bgSum DESC ) a ON a.unitId = isi.UNIT_ID WHERE dc.CODE_VALUE like '3205%' group by isi.UNIT_ID order by bgSum DESC,UNIT_NAME limit 10
### Cause: java.sql.SQLSyntaxErrorException: (conn=4994) Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sz_jdc.dc.CAPTION' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: (conn=4994) Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sz_jdc.dc.CAPTION' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
网友说:是由于默认的 MySQL 配置中 sql_mode
配置了 only_full_group_by
,需要 GROUP BY
中包含所有 在 SELECT 中出现的字段。
SELECT @@sql_mode;
解决办法:
1. 修改配置。去掉ONLY_FULL_GROUP_BY【最好不要这么干】
2. 在group by 后边增加select中字段,除了聚合函数【推荐这么搞】
我一开始非常不理解为什么要在group by 后边增加select中字段,除了聚合函数
举个例子:
现在要求:计算每个课程的学生人数
课程 | 人数 |
操作系统 | 56 |
计算机网络 | 37 |
你的sql应该是select course,count(*) from student group by course
但是 如果加上一列老师
课程 | 人数 | 老师 |
操作系统 | 56 | |
计算机网络 | 37 |
《操作系统》可能由三个不同的老师来教,这个时候你怎么办?
所以正确的应该是再加上一个分组条件,也就是为什么分组的时候select的字段为什么一定要出现在group by
课程 | 人数 | 老师 |
操作系统 | 36 | 程中恒 |
操作系统 | 20 | 萧敬腾 |
计算机网络 | 7 | 路小佳 |
计算机网络 | 30 | 刘桂江 |
你的sql应该是 select course,count(*),teacher from student group by course,teacher
参考:关于在分组的时候select的字段为什么一定要出现在group by_为什么groupby的参数中必须有select的参数-CSDN博客