使用 MySQL 查询按降序获取固定数量的结果

mysqlmysqli database

对于降序结果,使用 DESC。但是,LIMIT 用于获取固定数量的记录 −

select *from yourTableName order by yourColumnName DESC LIMIT yourLimitNumber;

首先我们创建一个表 −

mysql> create table DemoTable (Id int, Name varchar(100));
Query OK, 0 rows affected (0.73 sec)

示例

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values(100,'John');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(101,'Chris');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(102,'Robert');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(103,'Bob');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(104,'Adam');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(105,'James');
Query OK, 1 row affected (0.18 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

+------+--------+
| Id   | Name   |
+------+--------+
| 100  | John   |
| 101  | Chris  |
| 102  | Robert |
| 103  | Bob    |
| 104  | Adam   |
| 105  | James  |
+------+--------+
6 rows in set (0.00 sec)

按降序获取固定数量的记录 −

mysql> select *from DemoTable order by Name DESC LIMIT 3;

输出

+------+--------+
| Id   | Name   |
+------+--------+
| 102  | Robert |
| 100  | John   |
| 105  | James  |
+------+--------+
3 rows in set (0.00 sec)

相关文章