Home > Database > Mysql Tutorial > How to Get the Row ID After a MySQL INSERT/UPDATE with ON DUPLICATE KEY?

How to Get the Row ID After a MySQL INSERT/UPDATE with ON DUPLICATE KEY?

Barbara Streisand
Release: 2024-12-05 08:51:13
Original
566 people have browsed it

How to Get the Row ID After a MySQL INSERT/UPDATE with ON DUPLICATE KEY?

How to Retrieve the ID of a Row after INSERT/UPDATE Using MySQL ON DUPLICATE KEY

Inserting or updating data using the ON DUPLICATE KEY clause in MySQL can be a convenient way to handle duplicate key errors. However, it can be challenging to obtain the ID of the affected row after the operation.

One common assumption is that the LAST_INSERT_ID() function only returns the ID of newly inserted rows. However, in an ON DUPLICATE KEY scenario, it may also return the updated ID if a row was modified.

The Solution: LAST_INSERT_ID(expr)

To make LAST_INSERT_ID() meaningful for both inserts and updates, MySQL provides the following workaround:

INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE>
Copy after login

In this example, the id column is assumed to be the AUTO_INCREMENT primary key. By assigning LAST_INSERT_ID(id) to the id column on update, the function returns the updated ID.

Retrieving the Last Insert/Update ID

Once the workaround is in place, you can use the LAST_INSERT_ID() function to retrieve the ID of the row that was inserted or updated:

Copy after login

This approach allows you to retrieve the ID of the row affected by the INSERT/UPDATE operation without the need to run a separate query to fetch it.

The above is the detailed content of How to Get the Row ID After a MySQL INSERT/UPDATE with ON DUPLICATE KEY?. 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