为此,您可以将ORDER BY与LIMIT一起使用。在这里,LIMIT用于设置要获取的记录的限制(计数)。让我们首先创建一个表-
mysql> create table DemoTable1486 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1486(StudentName) values('Chris Brown'); mysql> insert into DemoTable1486(StudentName) values('David Miller'); mysql> insert into DemoTable1486(StudentName) values('John Doe'); mysql> insert into DemoTable1486(StudentName) values('John Smith'); mysql> insert into DemoTable1486(StudentName) values('Adam Smith'); mysql> insert into DemoTable1486(StudentName) values('Carol Taylor');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1486;
这将产生以下输出-
+-----------+--------------+ | StudentId | StudentName | +-----------+--------------+ | 1 | Chris Brown | | 2 | David Miller | | 3 | John Doe | | 4 | John Smith | | 5 | Adam Smith | | 6 | Carol Taylor | +-----------+--------------+ 6 rows in set (0.00 sec)
这是获取新添加的记录的查询-
mysql> select * from DemoTable1486 -> order by StudentId desc -> limit 3;
这将产生以下输出-
+-----------+--------------+ | StudentId | StudentName | +-----------+--------------+ | 6 | Carol Taylor | | 5 | Adam Smith | | 4 | John Smith | +-----------+--------------+ 3 rows in set (0.00 sec)