Home > Database > Mysql Tutorial > How to Use MySQL's ON DUPLICATE KEY UPDATE for Multiple Rows?

How to Use MySQL's ON DUPLICATE KEY UPDATE for Multiple Rows?

Linda Hamilton
Release: 2025-01-11 08:14:42
Original
539 people have browsed it

How to Use MySQL's ON DUPLICATE KEY UPDATE for Multiple Rows?

Efficiently Handling Multiple Rows with MySQL's ON DUPLICATE KEY UPDATE

MySQL offers a streamlined approach to managing multiple row insertions while simultaneously checking for and updating existing unique values. This is accomplished using the ON DUPLICATE KEY UPDATE clause. This feature allows for conditional updates or insertions of specific fields within a single query.

To selectively update existing rows and add new ones, leverage an alias or the VALUES keyword in conjunction with ON DUPLICATE KEY UPDATE.

MySQL 8.0.19 and later (Using an Alias):

INSERT INTO beautiful (name, age)
    VALUES
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
    AS new
ON DUPLICATE KEY UPDATE
    age = new.age
Copy after login

MySQL 8.0.19 and earlier (Using the VALUES Keyword):

INSERT INTO beautiful (name, age)
    VALUES
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
ON DUPLICATE KEY UPDATE
    age = VALUES(age)
Copy after login

These examples demonstrate how to update or insert data based on existing unique keys. If a unique key already exists, the specified fields are updated; otherwise, a new row is inserted. The VALUES keyword or the alias new references the values being inserted in the INSERT statement.

The above is the detailed content of How to Use MySQL's ON DUPLICATE KEY UPDATE for Multiple Rows?. For more information, please follow other related articles on the PHP Chinese website!

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