使用子查询从 MySQL 表获取第二大成绩?
我们首先创建一个表 -
mysql> create table DemoTable( Marks int ); Query OK, 0 rows affected (1.34 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable values(78); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(88); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(67); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(76); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values(98); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(86); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(89); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(99); Query OK, 1 row affected (0.12 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+-------+ | Marks | +-------+ | 78 | | 88 | | 67 | | 76 | | 98 | | 86 | | 89 | | 99 | +-------+ 8 rows in set (0.00 sec)
以下是从 MySQL 表中获取第二大成绩的查询 -
mysql> select Marks from DemoTable where Marks=(select MAX(Marks) from DemoTable where Marks < (select MAX(Marks) from DemoTable));
这将产生以下输出 -
+-------+ | Marks | +-------+ | 98 | +-------+ 1 row in set (0.03 sec)
Advertisements