mysql遇见Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggre的问题

Expression #2 of SELECT list is not in GROUP BY clause and contains 
nonaggregated column ‘xxxx’ which is not functionally 
dependent on columns in GROUP BY clause; this is incompatible with 
sql_mode=only_full_group_by

查阅资料发现,对于group by聚合操作,如果在select中的列没有在group by中出现,那么这个SQL是不合法的,因为列不在group by从句中,所以设置了sql_mode=only_full_group_by的数据库,在使用group by时就会报错,而5.7版本以后,默认是开启了该模式。

我们可以执行以下命令是否开启了

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 

我的msyql版本是5.7.31,所以默认就开启了这个
mysql遇见Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggre的问题_第1张图片

可以看到默认有ONLY_FULL_GROUP_BY,所以我们只要去掉这个就行了。

方案一:不能永久生效

去掉ONLY_FULL_GROUP_BY,重新设置值。

 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'; 

上面是改变了全局sql_mode,对于新建的数据库有效。对于已存在的数据库,则需要在对应的数据下执行

set session 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的配置文件
在配置文件下新增配置,然后保存重启即可

[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

你可能感兴趣的:(mysql遇见Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggre的问题)