简体   繁体   English

我可以从批量插入中检索lastInsertId吗?

[英]Can I retrieve the lastInsertId from a bulk insert?

INSERT INTO details (idactivity,user,hours,val,date) VALUES ('981','133','0','10500','2008-07-01'),('981','184','0','2750','2008-07-01'),('981','184','0','2750','2008-07-01')

(iddetails as details table PK) (iddetails如细节表PK)

Is there a way to get the 3 new iddetails and get them to the next bulk insert query? 有没有办法获得3个新的iddetails并让他们进入下一个批量插入查询?

INSERT INTO activity (idactivity,iddetails) VALUES('981',??),('981',??),('981',??)

There is a detailed discussion of the behavior of last_insert_id() with multi-row insert statements in the MySQL manual. 在MySQL手册中详细讨论了last_insert_id()与多行插入语句行为 Scroll down a little to the part with the red vertical bar beginning with the word "important". 向下滚动一下,红色垂直条以“重要”字样开头。

I think you have to do the initial inserts one at a time. 我认为你必须一次做一个初始插入。 MySQL's last_insert_id will just give you the id of the first element you insert with a multi-line insert statement like that. MySQL的last_insert_id只会为您提供插入的第一个元素的id,其中包含多行插入语句。 There may be issues if you have more than one process inserting lines at the same time. 如果您有多个进程同时插入行,则可能会出现问题。

However, (and I haven't verified this,) if you are using InnoDB tables, then the statement should be executed in an implicit transaction, so you should be able to assume that the ids generated were sequential. 但是,(我还没有验证这一点,)如果你使用InnoDB表,那么语句应该在一个隐式事务中执行,所以你应该能够假设生成的id是顺序的。

Another way, again, if you have transactions, is to lock the table, and update it's AUTO_INCREMENT property manually. 另一种方法,如果你有事务,就是锁定表,并手动更新它的AUTO_INCREMENT属性。 If you have 50 rows to insert, for instance, then bump it by 50. Then unlock the table, and insert your rows, explicitly using the ids you have reserved. 例如,如果要插入50行,则将其加50,然后解锁表,并使用您保留的ID显式插入行。 You will need transations for this (or at least table locks) so that you don't read the AUTO_INCREMENT, and then have someone insert a new row before you update it. 您将需要转换(或至少是表锁),以便您不读取AUTO_INCREMENT,然后让某人在更新之前插入新行。

据我所知,不是在mysql

If you used a datetime instead of just a date you could lookup the inserted id based on the user and the datetime values, but it is probably better so just not do a bulk insert if you need that data. 如果您使用日期时间而不仅仅是日期,则可以根据用户和日期时间值查找插入的ID,但它可能更好,因此如果您需要该数据,则不要进行批量插入。 Otherwise you end up running more queries anyway. 否则你最终会运行更多的查询。

you could add a database field for a GUID and store a random one with each record. 您可以为GUID添加数据库字段,并为每条记录存储随机的字段。 then another query could extract the IDs 然后另一个查询可以提取ID

Using SELECT last_insert_id( ) ; 使用SELECT last_insert_id(); query you can get the last inserted id. 查询您可以获取最后插入的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM