MySQL 5.7 错误:this is incompatible with sql_mode=only_full_group_by 的解决 (1020 views)

gHOST

2017-03-15 23:10:14

MySQL 升级到 5.7.5+ 之后,有时执查询会出现以下错误

[Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'information_schema.PROFILING.SEQ' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

这是因为 MySQL 的 sql_mode 导致的,详情见这里

在 MySQL 5.7 里 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, and NO_ENGINE_SUBSTITUTION

MySQL 5.7.5 添加了 ONLY_FULL_GROUP_BYSTRICT_TRANS_TABLES 模式。

MySQL 5.7.7 添加了 NO_AUTO_CREATE_USER 模式。

MySQL 5.7.8 添加了 ERROR_FOR_DIVISION_BY_ZERO, NO_ZERO_DATE, NO_ZERO_IN_DATE 模式。

更多关于 sql_mode 的信息可以参考这里

ONLY_FULL_GROUP_BY 模式下, target list 中的值要么是来自于聚集函数的结果,要么是来自于 group by list 中的表达式的值,否则 MySQL 就会拒绝这次查询。

解决办法

查看当前的 sql_mode

mysql> SELECT @@GLOBAL.sql_mode;
+-------------------------------------------------------------------------------------------------------------------------------------------+
| @@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 |
+-------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set

mysql> SELECT @@SESSION.sql_mode;
+-------------------------------------------------------------------------------------------------------------------------------------------+
| @@SESSION.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 |
+-------------------------------------------------------------------------------------------------------------------------------------------+

在 MySQL 的配置文件的 [mysqld] 区段里添加以下内容

...
[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
...

实际上就是在去掉了默认值里的 ONLY_FULL_GROUP_BY

重启 MySQL 问题解决。

参考:
http://www.wtoutiao.com/p/19dh3ec.html
http://www.tuicool.com/articles/AF73amz