Given the SQL code below:
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)
Why 3 rows? I would have thought both queries should return the same result since unique combinations of c exist.
Further
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)
the sum seems to be the sum of all the rows rather than the sum of the groupings
Any ideas why I’m seeing this strange behaviour?
Here is clearly mentioned
References:
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/