获取MySQL表的倒数第二行?

您需要使用ORDER BY子句来获取MySQL中表的倒数第二行。

语法如下。

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

为了理解上述语法,让我们创建一个表。创建表的查询如下。

create table secondLastDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(10)
   -> );

使用insert命令在表中插入一些记录。

查询如下。

insert into secondLastDemo(StudentName) values('Larry');
insert into secondLastDemo(StudentName) values('Carol');
insert into secondLastDemo(StudentName) values('Bob');
insert into secondLastDemo(StudentName) values('Sam');
insert into secondLastDemo(StudentName) values('Mike');
insert into secondLastDemo(StudentName) values('David');
insert into secondLastDemo(StudentName) values('Maxwell');
insert into secondLastDemo(StudentName) values('Robert');
insert into secondLastDemo(StudentName) values('James');
insert into secondLastDemo(StudentName) values('Chris');
insert into secondLastDemo(StudentName) values('Ramit');

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

查询如下。

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中表的倒数第二行的查询。

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

输出显示倒数第二个记录。

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