简体   繁体   中英

MySQL LAST_INSERT_ID Query

I've had a look at the official documentation but I'm still a bit confused.

Say I have a procedure and it runs and performs an insert and then I request LAST_INSERT_ID() , am I getting the last insert id from the insert just done by my instance of the procedure running or is it the last insert id on the table by any instance/session that's called the procedure?

For example say the last inserted record ID was 4 and I called the procedure and my insert would be id 5 but my insert fails will I get 4 being returned as the last insert id or a null/0 value?

That very link to the documentation page that you gave in the question has an answer:

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.

So, there is no race condition from other clients. You need to request the LAST_INSERT_ID() in the same connection as INSERT to get correct result.

As for, what happens when transaction is rolled back, it is undefined:

If the previous statement returned an error, the value of LAST_INSERT_ID() is undefined. For transactional tables, if the statement is rolled back due to an error, the value of LAST_INSERT_ID() is left undefined. For manual ROLLBACK, the value of LAST_INSERT_ID() is not restored to that before the transaction; it remains as it was at the point of the ROLLBACK.

The documentation you linked to says:

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 means you can safely rely on the value returned by LAST_INSERT_ID() . It is the most recent auto incremented value generated by the same instance of the code that calls LAST_INSERT_ID() . Of course, you have to call it right after the INSERT statement you want to get the value for, it cannot return the values generated by the second most recent INSERT statement or older.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM