可以看到,虽然我们得到了 SUM(b) 的值为 7000 是期望的,但是 a 的值为 abc 不是我们期望的。
MySQL 8.0 里的文档提到这么一句话
the query is processed by treating all rows as a single group, but the value selected for each named column is nondeterministic
在这个例子中,a 的值就是不确定的
当 WHERE 过滤条件中包含了 SELECT 列表中全部非聚合列的字段,则在开启 only_full_group_by 下也可以正常工作
In this case, every such column must be limited to a single value in theWHEREclause, and all such limiting conditions must be joined by logicalAND
mysql> SET SESSION sql_mode = sys.list_add(@@session.sql_mode, 'ONLY_FULL_GROUP_BY');
Query OK, 0 rows affected (0.01 sec)
mysql> SELECT a,SUM(b) FROM mytable;
ERROR 1140 (42000): In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'study.mytable.a'; this is incompatible with sql_mode=only_full_group_by
mysql> SELECT a, SUM(b) FROM mytable WHERE a = 'abc';
+------+--------+
| a | SUM(b) |
+------+--------+
| abc | 3000 |
+------+--------+
1 row in set (0.00 sec)
mysql> SELECT * FROM mytable1;
+----+------+------+-------+
| id | a | b | c |
+----+------+------+-------+
| 1 | abc | qrs | 1000 |
| 2 | abc | tuv | 2000 |
| 3 | def | qrs | 4000 |
| 4 | def | tuv | 8000 |
| 5 | abc | qrs | 16000 |
| 6 | def | tuv | 32000 |
+----+------+------+-------+
6 rows in set (0.00 sec)
mysql> SELECT a, b, SUM(c) FROM mytable1 WHERE a = 'abc' OR b = 'qrs';
ERROR 1140 (42000): In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'study.mytable1.a'; this is incompatible with sql_mode=only_full_group_by
mysql> SELECT a, b, SUM(c) FROM mytable1 WHERE a = 'abc' AND b = 'qrs';
ERROR 1140 (42000): In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'study.mytable.a'; this is incompatible with sql_mode=only_full_group_by