groupby报错not dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full

2022-11-28 16:02:52 浏览数 (1)

问题描述

MySQL执行如下group by 语句报错:1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘table_zjq.id’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

代码语言:javascript复制
select * from table_zjq group by column_name;

解决方法

上述报错大致是group开启了严格约束,不符合sql_mode=only_full_group_by规范,only_full_group_by约束在分组时,只能对该分组的字段进行查询。(注:MySQL5.7之后的版本才会有这个问题,MySQL5.7后默认的sql_mode=only_full_group_by) 可以解决该报错的方法如下:

重新设置sql_mode

查询当前数据库的sql_mode设置:

代码语言:javascript复制
select @@global.sql_mode

结果如下:

ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

去掉ONLY_FULL_GROUP_BY后重新设置,语句如下:

  • 单个库设置
代码语言:javascript复制
SET sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
  • 全局设置
代码语言:javascript复制
SET GLOBAL sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

修改配置文件

windows 修改安装目录下的my.ini 文件,Linux 修改/ etc/my.cnf 。都是对应的MySQL的配置文件地址,在文件的最后加上这行:

代码语言:javascript复制
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

执行如下命令,重启MySQL后问题解决。

systemctl restart mysqld

0 人点赞