问题描述
Cause: java.sql.SQLSyntaxErrorException: Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘XX’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
原因分析:
MySQL 5.7后,MySQL 默认开启了 sql_mode = only_full_group_by,对数据进行严格校验。如果代码中含有 group by 聚合操作,那么 select 中的列,除了使用聚合函数之外的(max()、min()、sum()等),都必须出现在 group by 中。
解决方案:
方案一:脚本修改sql_mode(重启会重置)
执行 sql 查询 sql_mode:
SELECT @@global.sql_mode;
查询结果:
ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
执行 sql 修改 sql_mode(去掉 ONLY_FULL_GROUP_BY):
SET GLOBAL sql_mode = ‘STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION’;
方案二:修改数据库配置(永久生效)
修改配置文件 my.ini,在 [mysqld] 模块下新增如下一行配置,重启 mysql 生效:
sql_mode = ‘STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION’;