MySQL中MAX函數與Group By一起使用的注意事項

來源:互聯網
上載者:User

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)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.