如何仅在 MySQL 中限制记录到最后五个结果
仅获取后五个记录,语法如下 −
select *from yourTableName order by yourColumnName DESC LIMIT 5;
我们先创建一个表 −
mysql> create table DemoTable820( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerName varchar(100) ); Query OK, 0 rows affected (0.53 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable820(CustomerName) values('Chris'); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable820(CustomerName) values('Robert'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable820(CustomerName) values('David'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable820(CustomerName) values('Bob'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable820(CustomerName) values('Carol'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable820(CustomerName) values('Adam'); Query OK, 1 row affected (0.08 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable820;
这将产生以下输出 −
+----+--------------+ | Id | CustomerName | +----+--------------+ | 1 | Chris | | 2 | Robert | | 3 | David | | 4 | Bob | | 5 | Carol | | 6 | Adam | +----+--------------+ 6 rows in set (0.00 sec)
以下查询可将记录限制到仅显示最后五个结果 −
mysql> select *from DemoTable820 order by Id DESC LIMIT 5;
这将产生以下输出 −
+----+--------------+ | Id | CustomerName | +----+--------------+ | 6 | Adam | | 5 | Carol | | 4 | Bob | | 3 | David | | 2 | Robert | +----+--------------+ 5 rows in set (0.00 sec)
广告