为此,您可以将GROUP BY与gregation function一起使用MAX()
。让我们首先创建一个表-
mysql> create table DemoTable1964 ( StudentName varchar(20), StudentAge int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1964 values('Chris',23); mysql> insert into DemoTable1964 values('David',34); mysql> insert into DemoTable1964 values('Chris',27); mysql> insert into DemoTable1964 values('Sam',31); mysql> insert into DemoTable1964 values('David',32); mysql> insert into DemoTable1964 values('David',37);
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1964;
这将产生以下输出-
+-------------+------------+ | StudentName | StudentAge | +-------------+------------+ | Chris | 23 | | David | 34 | | Chris | 27 | | Sam | 31 | | David | 32 | | David | 37 | +-------------+------------+ 6 rows in set (0.00 sec)
这是获取最长年龄的查询:
mysql> select StudentName,max(StudentAge) from DemoTable1964 group by StudentName;
这将产生以下输出-
+-------------+-----------------+ | StudentName | max(StudentAge) | +-------------+-----------------+ | Chris | 27 | | David | 37 | | Sam | 31 | +-------------+-----------------+ 3 rows in set (0.00 sec)