首页 > 代码库 > MySQL中Group By使用注意事项
MySQL中Group By使用注意事项
mysql> select * from test;+----+-------+------+-------+| id | name | age | class |+----+-------+------+-------+| 1 | qiu | 22 | 1 | | 2 | liu | 42 | 1 | | 4 | zheng | 20 | 2 | | 3 | qian | 20 | 2 | | 0 | wang | 11 | 3 | | 6 | li | 33 | 3 | +----+-------+------+-------+6 rows in set (0.00 sec)
如果想找到每个class里面的最大的age,则需要使用group by和max。
如下的sql语句,则输出结果有错误:
mysql> select id,name,max(age),class from test group by class;+----+-------+----------+-------+| id | name | max(age) | class |+----+-------+----------+-------+| 1 | qiu | 42 | 1 | | 4 | zheng | 20 | 2 | | 0 | wang | 33 | 3 | +----+-------+----------+-------+3 rows in set (0.00 sec)
虽然找到的age是最大的age,但是与之匹配的用户信息却不是真实的信息,而是group by分组后的第一条记录的基本信息。如果我使用以下的语句进行查找,则可以返回真实的结果。
mysql> select * from ( -> select * from test order by age desc) as b -> group by class;+----+-------+------+-------+| id | name | age | class |+----+-------+------+-------+| 2 | liu | 42 | 1 | | 4 | zheng | 20 | 2 | | 6 | li | 33 | 3 | +----+-------+------+-------+3 rows in set (0.00 sec)
distinct本来就是针对 “多列”的,如果想让单个列“distinct”,用group by
mysql> select a,b from abc;
+------+------+
| a | b |
+------+------+
| 7 | 9 |
| 7 | 1 |
| 7 | 1 |
+------+------+
3 rows in set (0.00 sec)
mysql> select distinct a,b from abc;
+------+------+
| a | b |
+------+------+
| 7 | 9 |
| 7 | 1 |
+------+------+
2 rows in set (0.00 sec)
mysql> select a, max(b) from abc group by a;
+------+--------+
| a | max(b) |
+------+--------+
| 7 | 9 |
+------+--------+
1 row in set (0.01 sec)
MySQL中Group By使用注意事项
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。