如何使用 MySQL 查询获得第四高的值?
若要获取第四高的值,请使用 LIMIT OFFSET 与 ORDER BY 联合使用。我们首先创建一个表格 -
mysql> create table DemoTable ( Amount int ); Query OK, 0 rows affected (0.88 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable values(980); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(670); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(890); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(995); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values(198); Query OK, 1 row affected (0.10 sec)
使用选择语句从表中显示所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+--------+ | Amount | +--------+ | 980 | | 670 | | 890 | | 995 | | 198 | +--------+ 5 rows in set (0.00 sec)
以下是获得第四高的值的查询 -
mysql> select *from DemoTable order by Amount desc limit 1 offset 3;
这将产生以下输出 -
+--------+ | Amount | +--------+ | 670 | +--------+ 1 row in set (0.00 sec)
广告