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.

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

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站