报错信息如下:
#4 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘t.dept_code’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
最近项目中上了新功能,同时做了数据库的备库方案,但是当应用访问备库时,出现部分分组sql查询报错。
原因是因为Sql语句SELECT后面的列包含了group by后面没有的列并且没有使用聚合函数。
经查询MySQL官网介绍:
https://dev.mysql.com/doc/refman/8.0/en/group-by-handling.html
https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sqlmode_only_full_group_by
由上面官网介绍得知,要么修改sql语句将未进行group by 的列,使用any_value() 处理;要么禁用ONLY_FULL_GROUP_BY(脚本如下)。
mysql> SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
mysql> SELECT @@GLOBAL.sql_mode;
+---------------------------------------------------------------+
| @@GLOBAL.sql_mode