MySQL LAST_INSERT_ID()与多条记录INSERT语句一起使用 [英] MySQL LAST_INSERT_ID() used with multiple records INSERT statement

查看:72
本文介绍了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.

所以有人可以确认这是否是在多个记录INSERT语句的上下文中LAST_INSERT_ID()的正常行为.所以我可以将代码作为基础.

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文档:

重要
如果您使用单个 INSERT 语句插入多行, LAST_INSERT_ID() 返回仅为第一个插入的行生成的值.这样做的原因是可以轻松重现相同的 INSERT 针对其他服务器的声明.

Important
If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.

这篇关于MySQL LAST_INSERT_ID()与多条记录INSERT语句一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆