how do i handle concurrent inserts in mysql table and fetch the correct insert id

天大地大妈咪最大 提交于 2019-12-30 07:18:09

问题


I am using adodb for PHP library.

For fetching the id at which the record is inserted I use this function

"$db->Insert_ID()"

I want to know if there are multiple and simultaneous inserts into the database table, will this method return me the correct inserted id for each record inserted ?

The reason I am asking this is because I use this last insert id for further processing of other records and making subsequent entries in the related tables.

Is this approach safe enough or am I missing something.

Please help me formulate a proper working plan for this so that I can use the last insert id for further inserts into the other table safely without having to mess up with the existing data.

Thanks


回答1:


Yes, it's safe for concurent use. That's because LAST_INSERT_ID() is per-connection, as explained here:

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.




回答2:


The $db->Insert_ID() will return you last insert id only so if you are inserting many records and want to get id of each last inserted row, then this will work successfully.




回答3:


I want to know if there are multiple and simultaneous inserts into the database table, will this method return me the correct inserted id for each record inserted ?

It will return only the most recently inserted id.
In order to get ids for multiple inserts, you will have to call INSERT_ID() after each statement is executed. IE:

INSERT INTO TABLE ....
INSERT_ID()

INSERT INTO TABLE ....
INSERT_ID()

...to get the id value for each insert. If you ran:

INSERT INTO TABLE ....
INSERT INTO TABLE ....
INSERT_ID()

...will only return the id for the last insert statement.

Is this approach safe enough or am I missing something.

It's safer than using SELECT MAX(id) FROM TABLE, which risks returning a value inserted by someone else among other things relating to isolation levels.



来源:https://stackoverflow.com/questions/2124200/how-do-i-handle-concurrent-inserts-in-mysql-table-and-fetch-the-correct-insert-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!