MySQL LAST_INSERT_ID() used with multiple records INSERT statement(MySQL LAST_INSERT_ID() 与多条记录 INSERT 语句一起使用)
问题描述
如果我用一个循环插入多条记录,执行单个记录插入,返回的最后一个插入 id 是,正如预期的那样,最后一个.但是如果我执行多条记录插入语句:
If I insert multiple records with a loop that executes a single record insert, the last insert id returned is, as expected, the last one. But if I do a multiple records insert statement:
INSERT INTO people (name,age)
VALUES ('William',25), ('Bart',15), ('Mary',12);
假设以上三个是插入表中的第一条记录.在插入语句之后,我希望最后一个插入 id 返回 3,但它返回了 1.有问题的语句的第一个插入 id.
Let's say the three above are the first records inserted in the table. After the insert statement I expected the last insert id to return 3, but it returned 1. The first insert id for the statement in question.
那么有人可以确认这是否是 LAST_INSERT_ID() 在多条记录 INSERT 语句的上下文中的正常行为.所以我可以基于它编写我的代码.
So can someone please confirm if this is the normal behavior of LAST_INSERT_ID() in the context of multiple records INSERT statements. So I can base my code on it.
推荐答案
是的.last_insert_id() 的这种行为是 在 MySQL 文档中记录:
Yes. This behavior of last_insert_id() is documented in the MySQL docs:
重要
如果您使用单个 INSERT<插入多行/a> 语句,LAST_INSERT_ID() 仅返回为第一个插入行生成的值.这样做的原因是为了可以轻松重现相同的 针对其他服务器的 INSERT 语句.
这篇关于MySQL LAST_INSERT_ID() 与多条记录 INSERT 语句一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL LAST_INSERT_ID() 与多条记录 INSERT 语句一起使用
基础教程推荐
- 带更新的 sqlite CTE 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
