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)

更新於:2020 年 6 月 20 日

232 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.