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

拟墨画扇 提交于 2019-11-30 23:13:01

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.

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.

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.

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