如何在 MySQL 中按 DESC 排序并显示前 3 条记录?
为此,你可以使用带有 LIMIT 的 ORDER BY DESC。让我们先创建一个表——
mysql> create table DemoTable ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserName varchar(100) ); Query OK, 0 rows affected (0.59 sec)
使用插入命令在表中插入一些记录——
mysql> insert into DemoTable(UserName) values('Chris'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(UserName) values('Robert'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(UserName) values('Bob'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(UserName) values('David'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(UserName) values('Mike'); Query OK, 1 row affected (0.10 sec)
使用 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)
广告