如何在MySQL表上仅选择3个有序行?
为此,可以将ORDERBY子句与LIMIT一起使用。让我们首先创建一个表-
mysql> create table DemoTable1551 -> ( -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> EmployeeName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1551(EmployeeName) values('Chris'); mysql> insert into DemoTable1551(EmployeeName) values('Robert'); mysql> insert into DemoTable1551(EmployeeName) values('Mike'); mysql> insert into DemoTable1551(EmployeeName) values('Sam'); mysql> insert into DemoTable1551(EmployeeName) values('David'); mysql> insert into DemoTable1551(EmployeeName) values('Adam');
使用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)