如何以升序顺序选择 MySQL 表中最后三行?
要按升序选择最后三行,请使用 ORDER BY DESC LIMIT,如下面的语法所示 −
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) -> ); Query OK, 0 rows affected (0.67 sec)
使用插入命令在表中插入一些记录 −
mysql> insert into DemoTable1579(Name) values('Robert'); Query OK, 1 row affected (0.37 sec) mysql> insert into DemoTable1579(Name) values('Bob'); Query OK, 1 row affected (0.48 sec) mysql> insert into DemoTable1579(Name) values('Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1579(Name) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1579(Name) values('Mike'); Query OK, 1 row affected (0.09 sec)
使用 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)
广告