简体   繁体   中英

MySQL LAST_INSERT_ID() question potential

If i have insert query for example:

INSERT INTO user(username) VALUES('admin');

And then get the id of the inserted record with

LAST_INSERT_ID();

Looks find but what happens if between the insert and LAST_INSERT_ID() another insert is executed.

How MySQL knows to return the correct id (for the first or second insert) since no parameter is passed to LAST_INSERT_ID();

Is it save to use this function?

Thanks

I'm supposing that you mean what happen if i'm connected to the MySQL server and executing an INSERT but others are also doing insert, like updating a table on a website while client are currently using it.

If you go take a look at the documentation https://dev.mysql.com/doc/refman/8.0/en/information-functions.html there is a point that answers your questions:

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.

This should be the same in MariaDB.

As discussed in the comment, you are wondering if you can use this in a php PDO environment. If you mean to use this directly from the database, it's a no, you won't be able to have the last inserted ID because you won't have the same client connection as PDO. If you want to use it directly from PDO please use the specific PDO function: http://php.net/manual/fr/pdo.lastinsertid.php , this should allow to do what you want.

If you insert multiple rows into a table using a single INSERT query, the LAST_INSERT_ID function returns the last insert id of the first row. ie

If your table id has 3 as column value and you will insert 4 rows in a single query then LAST_INSERT_ID will give you 4 instead of 7

If you insert 4 rows in 4 different insert query then LAST_INSERT_ID will give you 7

last_insert_id( ) Or mysqli_insert_id( ) will always return the id of last or most recent query. And also be noted that id field must have AUTO_INCREMENT enabled.

It doesn't give you the freedom to choose any specific table. Or you can't have id which is generated from your previous query.

So, from this point it serves a very small purpose. Only the last id , it doesn't matter which table.

To get last id from any specific table this query would be helpful : "SELECT id FROM table_name ORDER BY id DESC LIMIT 1"

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