如何在 MySQL 中按 ID 排序最后 5 条记录

mysqlmysqli database

您可以使用子查询来实现这一点。让我们首先创建一个表 −

mysql> create table DemoTable
(
   Id int
);
Query OK, 0 rows affected (0.68 sec)

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

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(115);
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable values(200);
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values(140);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(124);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(198);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(156);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(178);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(156);
Query OK, 1 row affected (0.43 sec)

以下是使用 select 语句显示表中的所有记录的查询 −

mysql> select *from DemoTable;

这将产生以下输出 −

+------+
| Id   |
+------+
| 100  |
| 115  |
| 200  |
| 140  |
| 124  |
| 198  |
| 156  |
| 178  |
| 156  |
+------+
9 rows in set (0.00 sec)

以下查询按 ID 排序获取最后 5 条记录 −

mysql> select *from(select *from DemoTable order by Id DESC limit 5)tbl
order by Id;

这将产生以下输出 −

+------+
| Id   |
+------+
| 156  |
| 156  |
| 178  |
| 198  |
| 200  |
+------+
5 rows in set (0.00 sec)

相关文章