如何在 MySQL 中獲取表的倒數第二行?


需要使用 ORDER BY 子句獲取 MySQL 表的倒數第二行。

語法如下。

select *from yourTableName order by yourColumnName DESC LIMIT 1,1;

為理解以上語法,讓我們建立一個表。建立表的查詢如下。

mysql> create table secondLastDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(10)
   -> );
Query OK, 0 rows affected (0.52 sec)

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

查詢如下。

mysql> insert into secondLastDemo(StudentName) values('Larry');
Query OK, 1 row affected (0.15 sec)
mysql> insert into secondLastDemo(StudentName) values('Carol');
Query OK, 1 row affected (0.09 sec)
mysql> insert into secondLastDemo(StudentName) values('Bob');
Query OK, 1 row affected (0.10 sec)
mysql> insert into secondLastDemo(StudentName) values('Sam');
Query OK, 1 row affected (0.09 sec)
mysql> insert into secondLastDemo(StudentName) values('Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into secondLastDemo(StudentName) values('David');
Query OK, 1 row affected (0.08 sec)
mysql> insert into secondLastDemo(StudentName) values('Maxwell');
Query OK, 1 row affected (0.10 sec)
mysql> insert into secondLastDemo(StudentName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into secondLastDemo(StudentName) values('James');
Query OK, 1 row affected (0.14 sec)
mysql> insert into secondLastDemo(StudentName) values('Chris');
Query OK, 1 row affected (0.11 sec)
mysql> insert into secondLastDemo(StudentName) values('Ramit');
Query OK, 1 row affected (0.08 sec)

使用 select 語句從表中展示所有記錄。

查詢如下。

mysql> select *from secondLastDemo;

以下是輸出結果。

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | Larry       |
| 2         | Carol       |
| 3         | Bob         |
| 4         | Sam         |
| 5         | Mike        |
| 6         | David       |
| 7         | Maxwell     |
| 8         | Robert      |
| 9         | James       |
| 10        | Chris       |
| 11        | Ramit       |
+-----------+-------------+
11 rows in set (0.00 sec)

以下是對 MySQL 表中獲取倒數第二行的查詢。

mysql> select *from secondLastDemo order by StudentId DESC LIMIT 1,1;

輸出會展示倒數第二條記錄。

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 10        | Chris       |
 +-----------+-------------+
1 row in set (0.00 sec)

更新於: 30-Jul-2019

瀏覽量:10K+

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.