Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ผลของ LAST_INSERT_ID() ใน MySQL เมื่อ INSERT หลายแถวพร้อมกัน

LAST_INSERT_ID() คืนลำดับที่สร้างล่าสุด แต่ในกรณี multiple-row insert จะคืนลำดับของ แถวแรกสุด (foremost inserted row) ที่ถูกแทรก

ตัวอย่าง

mysql> INSERT INTO Student(Name) VALUES('Ram'),('Mohan'),('Aryan');
Query OK, 3 rows affected (0.03 sec)
Records: 3 Duplicates: 0 Warnings: 0

คำสั่งแทรก 3 ค่าในตาราง Student ด้วย multiple-row insert ค่าของคอลัมน์ Id ตรวจสอบได้ดังนี้:

mysql> SELECT * FROM Student;
+----+-------+
| Id | Name  |
+----+-------+
| 1  | Raman |
| 2  | Rahul |
| 3  | Ram   |
| 4  | Mohan |
| 5  | Aryan |
+----+-------+
5 rows in set (0.00 sec)

ควรคืนค่า 5 แต่ LAST_INSERT_ID() คืนค่า 3:

mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
| 3                |
+------------------+
1 row in set (0.00 sec)

เพราะ 3 เป็นค่าของแถวแรกสุดที่ถูกแทรกในคำสั่ง multiple-row insert