Reputation: 829
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
Upvotes: 0
Views: 503
Reputation: 14987
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.
Upvotes: 2