如何訪問 MySQL 中最後插入的行?


如果你在列上使用了AUTO_INCREMENT,那麼你可以使用 last_insert_id() 方法。該方法獲取 MySQL 中最後插入記錄的 ID。

語法如下

SELECT LAST_INSERT_ID();

為了理解以上語法,讓我們建立一張表。建立表的查詢如下

mysql> create table LastInsertedRow
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > UserName varchar(20),  
   - > UserAge int
   - > );
Query OK, 0 rows affected (0.56 sec)

使用insert 命令在表中插入一些記錄。

查詢如下

mysql> insert into LastInsertedRow(UserName,UserAge) values('John',23);
Query OK, 1 row affected (0.19 sec)
mysql> insert into LastInsertedRow(UserName,UserAge) values('Carol',24);
Query OK, 1 row affected (0.16 sec)
mysql> insert into LastInsertedRow(UserName,UserAge) values('Bob',24);
Query OK, 1 row affected (0.08 sec)
mysql> insert into LastInsertedRow(UserName,UserAge) values('Larry',26);
Query OK, 1 row affected (0.09 sec)
mysql> insert into LastInsertedRow(UserName,UserAge) values('Maxwell',27);
Query OK, 1 row affected (0.10 sec)
mysql> insert into LastInsertedRow(UserName,UserAge) values('David',22);
Query OK, 1 row affected (0.10 sec)

使用select 語句顯示錶中所有記錄。

查詢如下

mysql> select *from LastInsertedRow;

輸出如下

+----+----------+---------+
| Id | UserName | UserAge |
+----+----------+---------+
|  1 | John     |      23 |
|  2 | Carol    |      24 |
|  3 | Bob      |      24 |
|  4 | Larry    |      26 |
|  5 | Maxwell  |      27 |
|  6 | David    |      22 |
+----+----------+---------+
6 rows in set (0.00 sec)

以下是獲取最後插入行的查詢

mysql> select last_insert_id();

輸出如下

+------------------+
| last_insert_id() |
+------------------+
|                6 |
+------------------+
1 row in set (0.00 sec)

如果你想要整行,則使用以下查詢

mysql> select *from LastInsertedRow where Id=(SELECT LAST_INSERT_ID());

輸出如下

+----+----------+---------+
| Id | UserName | UserAge |
+----+----------+---------+
|  6 | David    |      22 |
+----+----------+---------+
1 row in set (0.05 sec)

更新於: 2023 年 10 月 4 日

超過 2.5 萬次瀏覽

開啟您的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.