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)