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