[英]PDO Mysql prepared statement last_insert_id returns wrong value on multi-insert?
I noticed that if I prepare a multi-insert statement and execute it into MySQL via PDO, and then request the last_insert_id, I get the first ID of the multiple inserted rows, not the last one.我注意到如果我准备了一个多插入语句并通过 PDO 将它执行到 MySQL 中,然后请求 last_insert_id,我得到的是多个插入行的第一个 ID,而不是最后一个。 Specifically:具体来说:
"INSERT INTO test_table (value1, value2, value3) VALUES (1, 2, 3), (1, 2, 3)";
will create these rows on an empty table:将在一个空表上创建这些行:
ID value1 value2 value3
1 1 2 3
2 1 2 3
But the last_insert_id will return "1".但是 last_insert_id 将返回“1”。 Is this a known issue or am I doing something wrong?这是一个已知问题还是我做错了什么? Could someone verify/test/explain this?有人可以验证/测试/解释这一点吗? I am at a loss at what to do to get the proper last ID, save for doing an actual select which would be WAY slower.我不知道该怎么做才能获得正确的最后一个 ID,除了做一个会慢得多的实际选择。
It's correct mysql behavior这是正确的 mysql 行为
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
mysql> USE test;
Database changed
mysql> CREATE TABLE t (
-> id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
-> name VARCHAR(10) NOT NULL
-> );
Query OK, 0 rows affected (0.09 sec)
mysql> INSERT INTO t VALUES (NULL, 'Bob');
Query OK, 1 row affected (0.01 sec)
mysql> SELECT * FROM t;
+----+------+
| id | name |
+----+------+
| 1 | Bob |
+----+------+
1 row in set (0.01 sec)
mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
| 1 |
+------------------+
1 row in set (0.00 sec)
mysql> INSERT INTO t VALUES
-> (NULL, 'Mary'), (NULL, 'Jane'), (NULL, 'Lisa');
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM t;
+----+------+
| id | name |
+----+------+
| 1 | Bob |
| 2 | Mary |
| 3 | Jane |
| 4 | Lisa |
+----+------+
4 rows in set (0.01 sec)
mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
| 2 |
+------------------+
1 row in set (0.00 sec)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.