MySQL LAST_INSERT_ID() 函式有何用途?


MySQL LAST_INSERT_ID() 函式用於獲取 AUTO_INCREMENT 最近產生的序列號。

示例

在此示例中,我們建立了一個名為“Student”的表,該表有一個 AUTO_INCREMENT 列。我們在“Name”列中插入兩個值,當我們使用 INSERT_LAST_ID() 函式時,它返回最近產生的序列號,即 2。

mysql> Create table Student(Id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(5));
Query OK, 0 rows affected (0.13 sec)

mysql> Insert into student(Name) Values('Raman');
Query OK, 1 row affected (0.06 sec)

mysql> Insert into student(Name) Values('Rahul');
Query OK, 1 row affected (0.07 sec)

mysql> Select* from student;
+----+-------+
| Id | Name |
+----+-------+
| 1 | Raman |
| 2 | Rahul |
+---+-------+
2 rows in set (0.00 sec)

mysql> Select Last_insert_id();
+------------------+
| Last_insert_id() |
+------------------+
|                2 |
+------------------+
1 row in set (0.00 sec)

更新於:20-06-2020

232 次瀏覽

開啟您的職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.