如何在 MySQL 表中仅选择 3 个有序行?
mysqlmysqli database
为此,您可以将 ORDER BY 子句与 LIMIT 一起使用。让我们首先创建一个表 −
mysql> create table DemoTable1551 -> ( -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> EmployeeName varchar(20) -> ); Query OK, 0 rows affected (0.52 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1551(EmployeeName) values('Chris'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable1551(EmployeeName) values('Robert'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1551(EmployeeName) values('Mike'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1551(EmployeeName) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1551(EmployeeName) values('David'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1551(EmployeeName) values('Adam'); Query OK, 1 row affected (0.11 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1551;
这将产生以下输出 −
+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 1 | Chris | | 2 | Robert | | 3 | Mike | | 4 | Sam | | 5 | David | | 6 | Adam | +------------+--------------+ 6 rows in set (0.00 sec)
以下是在 MySQL 表中仅选择 3 个有序行的查询 −
mysql> select * from DemoTable1551 -> order by EmployeeId desc limit 0,3;
这将产生以下输出 −
+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 6 | Adam | | 5 | David | | 4 | Sam | +------------+--------------+ 3 rows in set (0.00 sec)