给定以下SQL代码:
create table A(a integer, b integer, c double);
insert into A(a, b, c)
values
(0, 0, 1.1),(1, 0, 1.2),(2, 0, 1.3),
(0, 1, 1.4),(1, 1, 1.5),(2, 1, 1.6),
(0, 2, 1.7),(1, 2, 1.8),(2, 2, 1.9),
(0, 0, 1.9),(1, 0, 1.8),(2, 0, 1.7),
(0, 1, 1.6),(1, 1, 1.5),(2, 1, 1.4),
(0, 2, 1.3),(1, 2, 1.2),(2, 2, 1.1)
mysql> select * from A where a = 0;
+------+------+------+
| a | b | c |
+------+------+------+
| 0 | 0 | 1.1 |
| 0 | 1 | 1.4 |
| 0 | 2 | 1.7 |
| 0 | 0 | 1.9 |
| 0 | 1 | 1.6 |
| 0 | 2 | 1.3 |
+------+------+------+
mysql> select * from A where a = 0 group by b;
+------+------+------+
| a | b | c |
+------+------+------+
| 0 | 0 | 1.1 |
| 0 | 1 | 1.4 |
| 0 | 2 | 1.7 |
+------+------+------+
3 rows in set (0.00 sec)为什么是3行?我认为这两个查询应该返回相同的结果,因为存在c的唯一组合。
进一步
mysql> select *, sum(c) from A group by b;
+------+------+------+--------+
| a | b | c | sum(c) |
+------+------+------+--------+
| 0 | 0 | 1.1 | 9 |
| 0 | 1 | 1.4 | 9 |
| 0 | 2 | 1.7 | 9 |
+------+------+------+--------+
3 rows in set (0.00 sec)总和似乎是所有行的总和,而不是分组的总和
你知道为什么我会看到这种奇怪的行为吗?
发布于 2011-08-29 19:20:10
清楚地提到了
在标准SQL中,包含GROUP BY子句的查询不能引用选择列表中未在GROUP BY子句中命名的非聚合列。例如,此查询在标准SQL中是非法的,因为选择列表中的名称列不会出现在GROUP BY中:
SELECT o.custid, c.name, MAX(o.payment)
FROM orders AS o, customers AS c
WHERE o.custid = c.custid
GROUP BY o.custid;若要使查询合法,必须从选择列表中省略name列或在GROUP BY子句中命名该列。
MySQL扩展了GROUP BY的使用,以便选择列表可以引用未在GROUP BY子句中指定的非聚集列。
参考:
http://rpbouman.blogspot.com/2007/05/debunking-group-by-myths.html
http://explainextended.com/2011/03/30/mysql-group-by-in-union/
http://20bits.com/articles/10-tips-for-optimizing-mysql-queries-that-dont-suck/
发布于 2011-08-29 19:14:37
Mysql是为数不多的几个之一(还有其他的吗?)允许像这样的“非法”SQL的数据库,在这些数据库中,您在选择的其他列上具有不带聚合函数的group by。
无论grouped by列的值是什么,它都会返回满足条件的第一行,而不是抛出错误。
https://stackoverflow.com/questions/7229296
复制相似问题