我怎样才能得到他年级中年龄最大的名字

时间:2017-04-18 07:01:42

标签: mysql

我怎样才能得到年龄最大的名字

表格信息:

mysql> select * from stu;
+----+------+------+-------+
| id | name | age  | grade |
+----+------+------+-------+
|  1 | a    |   11 |     1 |
|  2 | b    |   12 |     1 |
|  3 | c    |   13 |     1 |
|  4 | d    |   11 |     2 |
|  5 | e    |   12 |     2 |
|  6 | f    |   13 |     2 |
+----+------+------+-------+
6 rows in set (0.00 sec)

mysql> describe stu;
+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| id    | int(11) | NO   | PRI | NULL    | auto_increment |
| name  | char(1) | YES  |     | NULL    |                |
| age   | int(11) | YES  |     | NULL    |                |
| grade | int(11) | YES  |     | NULL    |                |
+-------+---------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
通过这种方式,我可以获得最大年龄和成绩,但我怎样才能得到年龄最大的名字。

mysql> select max(age),grade from stu group by grade;
+----------+-------+
| max(age) | grade |
+----------+-------+
|       13 |     1 |
|       13 |     2 |
+----------+-------+
2 rows in set (0.00 sec)

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

SELECT A.*
FROM STU A
INNER JOIN (SELECT MAX(AGE) AS MAX_AGE,GRADE FROM STU GROUP BY GRADE ) B ON A.GRADE = B.GRADE AND A.AGE= B.MAX_AGE

答案 1 :(得分:0)

试试这个:

select max(name), max(age),grade from  stu
group by grade