如何使用MySQL升序选择表的最后三行?
要按升序选择最后三行,请按照以下语法使用ORDERBYDESCLIMIT-
select * from (select * from yourTableName order by yourColumnName desc limit 3) anyAliasName order by yourColumnName ;
让我们首先创建一个表-
mysql> create table DemoTable1579 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1579(Name) values('Robert'); mysql> insert into DemoTable1579(Name) values('Bob'); mysql> insert into DemoTable1579(Name) values('Chris'); mysql> insert into DemoTable1579(Name) values('Sam'); mysql> insert into DemoTable1579(Name) values('Mike');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1579;
这将产生以下输出-
+----+--------+ | Id | Name | +----+--------+ | 1 | Robert | | 2 | Bob | | 3 | Chris | | 4 | Sam | | 5 | Mike | +----+--------+ 5 rows in set (0.00 sec)
以下是查询以升序选择表的最后三行-
mysql> select * from -> (select * from DemoTable1579 order by Id desc limit 3) t -> order by Id;
这将产生以下输出-
+----+-------+ | Id | Name | +----+-------+ | 3 | Chris | | 4 | Sam | | 5 | Mike | +----+-------+ 3 rows in set (0.00 sec)