要获得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 - > );
现在,您可以使用insert命令在表中插入一些记录。
查询如下
mysql> insert into lastRecordBeforeLastOne values(); mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Larry',23); mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Mike',19); mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Sam',24); mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Bob',26); mysql> insert into lastRecordBeforeLastOne(Name,Age) values('David',22); mysql> insert into lastRecordBeforeLastOne(Name,Age) values('James',29); mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Carol',21); mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Maxwell',29); mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Chris',25);
使用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)