mysql5.7.5及以上版本,默认启用了only_full_group_by SQL模式,这种模式下,分组的字段如果没有在查询列表中的话,那么检查就会不通过,导致SQL不能执行,报如下错误:
org.springframework.jdbc.BadSqlGrammarException: Error querying database. Cause: java.sql.SQLSyntaxErrorException: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column '具体的字段' 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,更新@@global.sql_mode为不包含only_full_group_by的值
SELECT @@global.sql_mode;
SET @@global.sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
方案二(重启生效):修改mysql的配置文件mysql-server.cnf,此文件一般位于/etc/my.cnf.d/目录下。低版本mysql为修改my.cnf(/etc/目录下)文件。
[mysqld]
#增加sql_mode
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
注意事项:具体配置文件在哪,一定要根据mysql的版本去查询,一般情况下,在/etc/my.cnf文件下都会指定包含的配置文件,根据这个配置文件可以找到实际配置sql_mode的文件。