开发者

MySQL and the chance of the wrong id being returned by LAST_INSERT_ID()

开发者 https://www.devze.com 2023-03-03 18:41 出处:网络
From what I have read LAST_INSERT_ID() retrieves the id of the last insert statement to run. If that the last insert statement run on your connection or the last insert run on the database for all con

From what I have read LAST_INSERT_ID() retrieves the id of the last insert statement to run. If that the last insert statement run on your connection or the last insert run on the database for all connections? I guess what I am trying to ask is: on a busy database driven website what are the chances the following code would return the wrong id, and is there a method to prevent that other then locking the database?

INSERT INTO example (string) VALUE ('something');
SELECT LAST_INSERT_ID();

Would PHP's mysql_insert_id() be a better solution, or should开发者_如何学C I just query for data that was just inserted and grab id that way?


Is that the last insert statement run on your connection or...

The last_insert on your connection.

Would PHP's mysql_insert_id() be a better solution

No, it's the same.

or should I just query for data that was just inserted and grab id that way?

That's way way slower

Link: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

Quote from that link:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消