简体   繁体   English

如何在多个记录插入中获取最后插入的ID?

[英]how get last inserted id in multiple record insert?

I am trying to write a tag system which I want allow users to insert multiple tag in a text input. 我正在尝试编写一个标签系统,我希望该系统允许用户在文本输入中插入多个标签。 And then I want insert each tag in tag_table and need their id for keep in tag_post_table . 然后,我想将每个标签插入tag_table并需要其ID保留在tag_post_table

I know that in multiple insert last_insert_id return the first record id. 我知道在多个插入中last_insert_id返回第一个记录ID。 Co can I add count of tags to last_insert_id for getting the real last id and use every id between them? 我可以将标记计数添加到last_insert_id以获得真实的最后一个ID并使用它们之间的每个ID吗? Is this reliable? 这可靠吗?

I read this article, but I don't understand it completely 我读了这篇文章,但我不太了解

http://dev.mysql.com/doc/refman/5.1/en/innodb-auto-increment-handling.html http://dev.mysql.com/doc/refman/5.1/en/innodb-auto-increment-handling.html

As I understand this article : 据我了解, 这篇文章

With innodb_autoinc_lock_mode set to 0 (“traditional”) or 1 (“consecutive”), the auto-increment values generated by any given statement will be consecutive, without gaps, because the table-level AUTO-INC lock is held until the end of the statement, and only one such statement can execute at a time. 在将innodb_autoinc_lock_mode设置为0(“传统”)或1(“连续”)的情况下,任何给定语句生成的自动增量值将是连续的,没有间隙,因为表级AUTO-INC锁定将一直保持到结束。该语句,一次只能执行一个这样的语句。

Setting innodb_autoinc_lock_mode to 0 or 1 guarantees that the auto incemented ids are consecutive. innodb_autoinc_lock_mode设置为0或1可确保自动增加的ID是连续的。

So the ID you get from LAST_INSERT_ID is the first of the new IDs and LAST_INSERT_ID + "the number of affected rows" is the last of the new IDs. 因此,您从LAST_INSERT_ID获得的ID是新ID的第一个,而LAST_INSERT_ID +“受影响的行数”是新ID的后一个。

Also LAST_INSTERT_ID is not affected by other connections LAST_INSTERT_ID也不受其他连接的影响

The ID that was generated is maintained in the server on a per-connection basis. 生成的ID在每个连接的服务器中维护。 This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. 这意味着函数返回给定客户端的值是针对该客户端影响AUTO_INCREMENT列的最新语句生成的第一个AUTO_INCREMENT值。 This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. 即使其他客户端生成自己的AUTO_INCREMENT值,该值也不会受到其他客户端的影响。 This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions. 此行为可确保每个客户端都可以检索自己的ID,而不必担心其他客户端的活动,也不需要锁或事务。

But notice, that there may be wrong results, if you use INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE ... . 但是请注意,如果您使用INSERT ... ON DUPLICATE KEY UPDATEINSERT IGNORE ... ,可能会导致错误的结果。 But I have not tested this. 但是我还没有测试过。

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

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