如何獲取來自 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 次瀏覽

開啟你的 職業

完成課程,獲得認證

開始
廣告
© . All rights reserved.