Home > Database > Mysql Tutorial > How to Update Existing Rows During an INSERT Using MySQL's ON DUPLICATE KEY UPDATE?

How to Update Existing Rows During an INSERT Using MySQL's ON DUPLICATE KEY UPDATE?

Mary-Kate Olsen
Release: 2024-11-30 02:30:13
Original
591 people have browsed it

How to Update Existing Rows During an INSERT Using MySQL's ON DUPLICATE KEY UPDATE?

Using "INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE"

When performing an insert operation with MySQL, it is possible to update existing rows if a unique key conflict occurs. This can be achieved using the "INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE" syntax.

In the given query, it is intended to insert rows from a temporary table ('tmp') into the 'lee' table. If a row with the same unique key ("id" in this case) already exists in 'lee', the query should update specific columns to the values from the 'tmp' table.

The syntax for the UPDATE clause in this scenario is as follows:

ON DUPLICATE KEY UPDATE column1=SELECT_column1, column2=SELECT_column2, ...
Copy after login

Here, "column1" refers to a column in the 'lee' table, and "SELECT_column1" refers to the corresponding column in the SELECT clause. By specifying these pairs, MySQL determines which columns to update with the new values from the SELECT.

For the provided query, the UPDATE clause would look like:

ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, inadur=t.inadur, inadist=t.inadist, smlct=t.smlct, smldur=t.smldur, smldist=t.smldist, larct=t.larct, lardur=t.lardur, lardist=t.lardist, emptyct=t.emptydur, emptydur=t.emptydur
Copy after login

This ensures that the columns "entct", "inact", "inadur", and so on, are updated with the values from the corresponding columns in the temporary table when a duplicate key is encountered.

The above is the detailed content of How to Update Existing Rows During an INSERT Using MySQL's ON DUPLICATE KEY UPDATE?. 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