mysql语法错误:this is incompatible with sql_mode=only_full_group_by

Mysql5.7版本之后对sql_mode做了修改,其中 ONLY_FULL_GROUP_BY 成为了默认模式之一。

执行命令:SELECT @@sql_mode; 可查看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

像oracle数据库采用的就是开启ONLY_FULL_GROUP_BY 模式。

简单理解ONLY_FULL_GROUP_BY模式,用于限制group by语法,要求select的字段要和group by的字段一致,保证select字段的唯一性。否则会造成搜索引擎不知道该返回哪一条。

比如有一张temp表:    

group_id name age
1 AA 34
2 BB 43
2 CC 12
3 DD 45

执行SQL:select group_id,name from temp group by group_id

返回结果中group_id为2的数据肯定会变成只有一条,但对应的name字段的值不唯一性,所以会抛出异常信息:

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

解决方案:

方案一:

使用mysql函数 any_value(field) 用于包含非分组字段的出现

比如:select group_id,any_value(name) from temp group by group_id

这样就不用关闭ONLY_FULL_GROUP_BY 模式

方案二:

修改mysql配置文件my.ini (linux系统修改my.cnf),把 ONLY_FULL_GROUP_BY 从sql_mode中去掉

sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

如果没有以上配置就添加到[mysqld]中,注意:需要重启mysql服务生效。




猜你喜欢

转载自blog.csdn.net/github_39325328/article/details/79556917