Home > Database > Mysql Tutorial > How to Retrieve IDs After Inserting Multiple Rows in MySQL?

How to Retrieve IDs After Inserting Multiple Rows in MySQL?

Mary-Kate Olsen
Release: 2024-12-24 10:57:10
Original
351 people have browsed it

How to Retrieve IDs After Inserting Multiple Rows in MySQL?

Inserting Multiple Rows with ID Retrieval in MySQL

Inserting data into a MySQL table typically returns the ID of the newly created row via the LAST_INSERT_ID() function. However, when inserting multiple rows, obtaining an array of IDs can be challenging.

Bulk Insertion with InnoDB

For InnoDB tables using recent MySQL versions, you can utilize the combination of LAST_INSERT_ID() and ROW_COUNT() to retrieve the inserted IDs. InnoDB provides sequential auto-increment IDs for bulk inserts when the innodb_autoinc_lock_mode setting is 0 (traditional) or 1 (consecutive).

Retrieving ID Range

Assuming a bulk insert statement has been executed:

INSERT INTO table (`column1`, `column2`) VALUES ..., ..., ...
Copy after login

You can calculate the range of IDs for the newly inserted rows using the following formula:

INSERTED_ID_RANGE = [LAST_INSERT_ID(), LAST_INSERT_ID() + ROW_COUNT() - 1]
Copy after login

Example

Consider the following bulk insert:

INSERT INTO table (`column1`, `column2`)
VALUES (1, 'value 1'), (2, 'value 2'), (3, 'value 3');
Copy after login

Assuming the LAST_INSERT_ID() after the insertion is 5, the inserted ID range would be:

[5, 5 + ROW_COUNT() - 1] = [5, 5 + 3 - 1] = [5, 7]
Copy after login

Therefore, the array of inserted IDs would be [5, 6, 7].

The above is the detailed content of How to Retrieve IDs After Inserting Multiple Rows in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template