如何在 MySQL 中获取表中的倒数第二条记录?


要获得倒数第二条记录,即 MySQL 中的倒数第二条记录,您需要使用子查询。

语法如下

SELECT *FROM
(SELECT *FROM yourTableName ORDER BY yourIdColumnName DESC LIMIT 2)
anyAliasName
ORDER BY yourIdColumnName LIMIT 1;

我们先创建一个表。创建表的查询如下

mysql> create table lastRecordBeforeLastOne
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > Name varchar(20) DEFAULT 'John',
   - > Age int DEFAULT 18
   - > );
Query OK, 0 rows affected (0.79 sec)

现在,您可以使用插入命令插入一些记录到表中。

查询如下

mysql> insert into lastRecordBeforeLastOne values();
Query OK, 1 row affected (0.21 sec)
mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Larry',23);
Query OK, 1 row affected (0.19 sec)
mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Mike',19);
Query OK, 1 row affected (0.20 sec)
mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Sam',24);
Query OK, 1 row affected (0.22 sec)
mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Bob',26);
Query OK, 1 row affected (0.13 sec)
mysql> insert into lastRecordBeforeLastOne(Name,Age) values('David',22);
Query OK, 1 row affected (0.23 sec)
mysql> insert into lastRecordBeforeLastOne(Name,Age) values('James',29);
Query OK, 1 row affected (0.14 sec)
mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Carol',21);
Query OK, 1 row affected (0.23 sec)
mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Maxwell',29);
Query OK, 1 row affected (0.18 sec)
mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Chris',25);
Query OK, 1 row affected (0.14 sec)

使用 select 语句显示表中的所有记录。

查询如下

mysql> select *from lastRecordBeforeLastOne;

以下是输出

+----+---------+------+
| Id | Name    | Age  |
+----+---------+------+
|  1 | John    |   18 |
|  2 | Larry   |   23 |
|  3 | Mike    |   19 |
|  4 | Sam     |   24 |
|  5 | Bob     |   26 |
|  6 | David   |   22 |
|  7 | James   |   29 |
|  8 | Carol   |   21 |
|  9 | Maxwell |   29 |
| 10 | Chris   |   25 |
+----+---------+------+
10 rows in set (0.00 sec)

这是获取 MySQL 中第二条最后一条记录的查询

mysql> SELECT *FROM
   - > (SELECT *FROM lastRecordBeforeLastOne ORDER BY Id DESC LIMIT 2) tbl1
   - > ORDER BY Id LIMIT 1;

以下是输出

+----+---------+------+
| Id | Name    | Age  |
+----+---------+------+
|  9 | Maxwell |   29 |
+----+---------+------+
1 row in set (0.00 sec)

更新日期:30-Jul-2019

4K+ 次浏览

开启您的职业生涯

完成课程认证

开始
广告