如何获取来自 MySQL 表的新增记录?


为此,你可以将 ORDER BY 与 LIMIT 配合使用。此处,LIMIT 用来设置要获取的记录的限制(计数)。我们先创建一个表 −

mysql> create table DemoTable1486
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (0.66 sec)

使用 insert 命令在表中插入一些记录 −

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)

更新于: 11-12-2019

543 次浏览

开启你的 职业

完成课程,获得认证

开始
广告