从数据库按升序排列 id 查询最后 3 行?
可以使用子查询。以下是语法 −
SELECT * FROM ( SELECT * FROM yourTableName ORDER BY yourIdColumnName DESC LIMIT 3 ) anyAliasName ORDER BY yourIdColumnName;
我们先创建一个表 −
mysql> create table DemoTable ( ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientName varchar(100) ); Query OK, 0 rows affected (0.60 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(ClientName) values('Larry'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(ClientName) values('Chris'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(ClientName) values('Bob'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(ClientName) values('David'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(ClientName) values('Carol'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(ClientName) values('Robert'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(ClientName) values('Sam'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(ClientName) values('Mike'); Query OK, 1 row affected (0.12 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+----------+------------+ | ClientId | ClientName | +----------+------------+ | 1 | Larry | | 2 | Chris | | 3 | Bob | | 4 | David | | 5 | Carol | | 6 | Robert | | 7 | Sam | | 8 | Mike | +----------+------------+ 8 rows in set (0.00 sec)
以下是按 id ASC 升序查询数据库最后 3 行的查询 −
mysql> SELECT * FROM ( SELECT * FROM DemoTable ORDER BY ClientId DESC LIMIT 3 ) tbl ORDER BY ClientId ASC;
这将产生以下输出 −
+----------+------------+ | ClientId | ClientName | +----------+------------+ | 6 | Robert | | 7 | Sam | | 8 | Mike | +----------+------------+ 3 rows in set (0.00 sec)
广告