如何在MySQL中选择最后两行?
要选择最后两行,请使用ORDERBYDESCLIMIT2。
让我们首先创建一个表-
create table DemoTable763 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100) );
使用插入命令在表中插入一些记录-
insert into DemoTable763(FirstName) values('John'); insert into DemoTable763(FirstName) values('Sam'); insert into DemoTable763(FirstName) values('Carol'); insert into DemoTable763(FirstName) values('David'); insert into DemoTable763(FirstName) values('Bob');
使用select语句显示表中的所有记录-
select *from DemoTable763;
这将产生以下输出-
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Sam | | 3 | Carol | | 4 | David | | 5 | Bob | +----+-----------+ 5 rows in set (0.00 sec)
以下是在MySQL中选择最后两行的查询-
select *from DemoTable763 order by Id DESC LIMIT 2;
这将产生以下输出-
+----+-----------+ | Id | FirstName | +----+-----------+ | 5 | Bob | | 4 | David | +----+-----------+ 2 rows in set (0.00 sec)