donglu8344812 2015-06-24 13:57
浏览 159
已采纳

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

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.

I know that in multiple insert last_insert_id return the first record id. Co can I add count of tags to last_insert_id for getting the real last id and use every id between them? 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

  • 写回答

1条回答 默认 最新

  • douhensheng1131 2015-06-24 14:57
    关注

    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.

    Setting innodb_autoinc_lock_mode to 0 or 1 guarantees that the auto incemented ids are consecutive.

    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.

    Also LAST_INSTERT_ID is not affected by other connections

    The ID that was generated is maintained in the server on a per-connection basis. 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. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. 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.

    But notice, that there may be wrong results, if you use INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE .... But I have not tested this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效