为此,可以将ORDER BY DESC与LIMIT一起使用。让我们首先创建一个表-
mysql> create table DemoTable ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserName varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(UserName) values('Chris'); mysql> insert into DemoTable(UserName) values('Robert'); mysql> insert into DemoTable(UserName) values('Bob'); mysql> insert into DemoTable(UserName) values('David'); mysql> insert into DemoTable(UserName) values('Mike');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+--------+----------+ | UserId | UserName | +--------+----------+ | 1 | Chris | | 2 | Robert | | 3 | Bob | | 4 | David | | 5 | Mike | +--------+----------+ 5 rows in set (0.00 sec)
以下是在MySQL列上申请ORDER BY DESC后显示前3条记录的查询-
mysql> select *from DemoTable order by UserId DESC LIMIT 0,3;
这将产生以下输出-
+--------+----------+ | UserId | UserName | +--------+----------+ | 5 | Mike | | 4 | David | | 3 | Bob | +--------+----------+ 3 rows in set (0.00 sec)