在具有相似学生姓名的记录中从 MySQL 中获取最大年龄
为此,您可以将 GROUP BY 与聚合函数 MAX() 搭配使用。我们首先创建一个表 −
mysql> create table DemoTable1964 ( StudentName varchar(20), StudentAge int ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1964 values('Chris',23); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1964 values('David',34); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1964 values('Chris',27); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1964 values('Sam',31); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1964 values('David',32); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1964 values('David',37); Query OK, 1 row affected (0.00 sec)
使用 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)
广告