mysql group by 报错Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated c

当使用group by的语句中,select后面跟的列,在group by后面没有时,会报以下错误:

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

这是MySQL8.0默认开启only_full_group_by模式导致的,该模式限定select后面跟的列,在group by后面必须要有。

解决方式一:该方式重启mysql会失效

1、查询sql_mode:

select @@session.sql_mode;

ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

2、重新设置sql_mode,删除ONLY_FULL_GROUP_BY

set @@global.sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'

解决方式二

修改配置文件my.cnf

找到my.cnf,添加一下配置:

sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

重启mysql即可。
service mysqld restart

好了, 以上是本文所有内容,希望对大家有所帮助,也希望大家对码农之家多多支持,你们的支持是我创作的动力!祝大家生活愉快!    

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>