如何在 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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP