起因
最近将一个项目的MySQL升级到5.7,出现类似下面的错误:
ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘yourdb.yourtable.yourfield’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
说明
这个是由于MySQL在5.7版本中添加了一个sql_mode: ONLY_FULL_GROUP_BY
,当配置了此sql_mode后,select语句中要查询的字段必须严格是group by语句中的字段或者是聚合函数。
测试
1 | mysql> select version(); |
解决
修改sql
将需要查询的列加入到group by
语句中。1
2
3
4
5
6
7mysql> select b.user_id, a.account, sum(b.order_money) as total_money from user_order b left join user a on b.user_id = a.id group by b.user_id, a.account;
+---------+----------+-------------+
| user_id | account | total_money |
+---------+----------+-------------+
| 1 | zhangsan | 3 |
| 2 | lisi | 5 |
+---------+----------+-------------+
去除sql_mode中的ONLY_FULL_GROUP_BY
首先查询当前的sql_mode,分为全局的和当前session的。1
2
3
4
5
6
7
8
9
10
11
12
13mysql> 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 |
+-------------------------------------------------------------------------------------------------------------------------------------------+
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 |
+-------------------------------------------------------------------------------------------------------------------------------------------+
然后对sql_mode进行修改1
2mysql> 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';
mysql> 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';
再执行初始的查询sql语句:1
2
3
4
5
6
7mysql> select b.user_id, a.account, sum(b.order_money) as total_money from user_order b left join user a on b.user_id = a.id group by a.id, a.account;
+---------+----------+-------------+
| user_id | account | total_money |
+---------+----------+-------------+
| 1 | zhangsan | 3 |
| 2 | lisi | 5 |
+---------+----------+-------------+
参考文章: