sql查询报错:only_full_group_by解决方案
问题原因:
在 MySQL 5.7 后的版本,当 SQL 语句有 group by 关键词时,有时执行 SQL 会提示如下异常信息:
###
The error occurred while setting parameters
Cause: java.sql.SQLSyntaxErrorException: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sanyuan_db.sys_user.user_id' 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: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sanyuan_db.sys_user.user_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
造成异常的原因为 MySQL 5.7 版本后默认的 sql 配置是: sql_mode=ONLY_FULL_GROUP_BY,这个配置严格执行了"SQL92标准",如果 select 的字段和 group by 的字段没有同时出现,则会报错。
解决方案:
一、windows版本:
windows本地安装的mysql版本是8.的版本:
找到my.ini文件
注意:若安装的mysql8找不到my.ini文件(若能找到这个文件忽略1、2、3步,直接第4步)
1.打开隐藏的文件夹
win11举例:查看–显示–隐藏的项目
2.找到ProgramData文件夹
3.即可找到my.ini文件
4.编辑这个文件
将这块改成如图
自行复制:
sql-mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
二、linux版本:
1.找到my.cnf文件
文件地址一般在:/etc/my.cnf,/etc/mysql/my.cnf
2.编辑my.cnf文件
文件地址一般在:/etc/my.cnf,/etc/mysql/my.cnf
3.找到sql-mode的位置,去掉ONLY_FULL_GROUP_BY
4.然后重启MySQL
service mysql restart
注:有的my.cnf中可能没有sql-mode,需要在[mysqld]下追加:
sql-mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION