执行
SELECT *FROM test WHERE id>1 GROUP BY name having AVG(age)>10 ORDER BY id desc limit 1
提示错误
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'aaa.test.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by in
这个错误是由于 MySQL 的新版本中默认开启了ONLY_FULL_GROUP_BY
模式,即在 GROUP BY 语句中的 SELECT 列表中,只能包含分组或聚合函数,不能包含其他列
临时解决方案:
执行
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';
仅对下次连接生效,不影响当前会话,且MySQL重启后失效,因为MySQL重启时会重新读取配置文件里对应值,如果需永久生效需要修改配置文件里的值。
永久解决方案
修改/etc/my.cnf,将sql_mode=中的only_full_group_by给删掉
保存退出,重启服务器,即可永久生效