Retrieving the Last Inserted Ids for Multiple Rows

How to get inserted IDs of multiple rows on one INSERT?

MySQL & MariaDB have the LAST_INSERT_ID() function, and it returns the id generated by the most recent INSERT statement in your current session.

But when your INSERT statement inserts multiple rows, LAST_INSERT_ID() returns the first id in the set generated.

In such a batch of multiple rows, you can rely on the subsequent id's being consecutive. The MySQL JDBC driver depends on this, for example.

If the rows you insert include a mix of NULL and non-NULL values for the id column, you have a risk of messing up this assumption. The JDBC driver returns the wrong values for the set of generated id's.

Getting the primary key ID of the last inserted row to run multiple insert operations

You can use PDO's lastInsertId method like this

$item_id = $pdo->lastInsertId();

http://php.net/manual/en/pdo.lastinsertid.php

how get last inserted id in multiple record insert?

As I understand this article:

With innodb_autoinc_lock_mode set to 0 (“traditional”) or 1 (“consecutive”), the auto-increment values generated by any given statement will be consecutive, without gaps, because the table-level AUTO-INC lock is held until the end of the statement, and only one such statement can execute at a time.

Setting innodb_autoinc_lock_mode to 0 or 1 guarantees that the auto incemented ids are consecutive.

So the ID you get from LAST_INSERT_ID is the first of the new IDs and LAST_INSERT_ID + "the number of affected rows" is the last of the new IDs.

Also LAST_INSTERT_ID is not affected by other connections

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.

But notice, that there may be wrong results, if you use INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE .... But I have not tested this.



Related Topics



Leave a reply



Submit