如何從包含學生分數的表中獲取第 2 高的值?


要獲取第 2 高的值,請使用 ORDER BY DESC 以及 LIMIT 1,1。我們首先建立一個表 −

mysql> create table DemoTable
(
   StudentScore int
);
Query OK, 0 rows affected (0.56 sec)

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

mysql> insert into DemoTable values(89);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(69);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(97);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(99);
Query OK, 1 row affected (0.12 sec)

使用 select 語句從表中顯示所有記錄 −

mysql> select *from DemoTable;

這會生成以下輸出 −

+--------------+
| StudentScore |
+--------------+
|           89 |
|           69 |
|           97 |
|           99 |
+--------------+
4 rows in set (0.00 sec)

以下是獲取第 2 高值所需的查詢 −

mysql> select *from DemoTable order by StudentScore DESC limit 1,1;

這會生成以下輸出 −

+--------------+
| StudentScore |
+--------------+
|           97 |
+--------------+
1 row in set (0.00 sec)

更新於: 2019 年 9 月 25 日

608 次瀏覽

開啟您的 職業生涯

完成課程並獲得認證

開始吧
廣告
© . All rights reserved.