在 MySQL 中選擇第 n 個高值


以下是在 MySQL 中選擇第 n 個最高值的語法 −

select distinct(yourColumnName) from yourTableName order by yourColumnName DESC limit (NthValue-1),1;

我們首先建立一個表 −

mysql> create table DemoTable1594
   -> (
   -> Marks int
   -> );
Query OK, 0 rows affected (0.49 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable1594 values(76);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1594 values(95);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1594 values(56);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1594 values(96);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1594 values(89);
Query OK, 1 row affected (0.19 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select * from DemoTable1594;

這將生成以下輸出 −

+-------+
| Marks |
+-------+
|    76 |
|    95 |
|    56 |
|    96 |
|    89 |
+-------+
5 rows in set (0.00 sec)

以下是選擇第 n 個最高值的查詢 −

mysql> select distinct(Marks) from DemoTable1594 order by Marks DESC limit 2,1;

這將生成以下輸出 −

+-------+
| Marks |
+-------+
|    89 |
+-------+
1 row in set (0.00 sec)

更新日期: 2019 年 12 月 16 日

215 次瀏覽

開啟你的 事業

完成課程,獲得認證

開始
廣告