MySQL 如何从表中获取新添加的记录
为此,您可以使用带有LIMIT的ORDER BY。在这里,LIMIT用于设置要获取的记录的限制(计数)。让我们首先创建一个表−
mysql> create table DemoTable1486
-> (
-> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentName varchar(20)
-> );
Query OK, 0 rows affected (0.66 sec)
使用插入命令在表中插入一些记录−
mysql> insert into DemoTable1486(StudentName) values('Chris Brown');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1486(StudentName) values('David Miller');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1486(StudentName) values('John Doe');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1486(StudentName) values('John Smith');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1486(StudentName) values('Adam Smith');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1486(StudentName) values('Carol Taylor');
Query OK, 1 row affected (0.16 sec)
使用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)
阅读更多:MySQL 教程
极客教程