MySQL中MAX函数与GroupBy⼀起使⽤的注意事项(转)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;
+----+-------+----------+-------+
groupby是什么函数| 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)
原⽂来⾃:blog.csdn/magicharvey/article/details/21372813?utm_source=tuicool&utm_medium=referral
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论