简体   繁体   中英

LAST_INSERT_ID after restarting MySQL

I'm trying to retrieve the LAST_INSERT_ID by following statements after inserting a new record, it works fine.

SELECT LAST_INSERT_ID();

The problem

When Inserting a new record in table and restart MySQL Server and then trying to retrieve LAST_INSERT_ID , it gets 0 value!

LAST_INSERT_ID just works before restarting MySQL or rebooting system ?

Any help would be appreciated.

as stated in MySQL Docs ,

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.

Which means - after restart for your set of statements there is no statement affecting AUTO_INCREMENT value, so the value is undefined.

See this text in the LAST_INSERT_ID manual page:

The ID that was generated is maintained in the server on a per-connection basis. 

If you restart the server, or disconnect and reconnect againg, then you are not using the same connection as when you did the insert, so that's why you get 0

As it was already stated based on MySQL Reference Manual : function_last-insert-id :

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 .

To get what you need, just make a new query:

SELECT MAX(ID) FROM ExampleTable;

in case you can't use LAST_INSERT_ID in the intended way.

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