"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to efficiently INSERT or UPDATE rows based on two conditions in MySQL?

How to efficiently INSERT or UPDATE rows based on two conditions in MySQL?

Posted on 2025-04-20
Browse:319

How Can I Efficiently INSERT or UPDATE a MySQL Row Based on Two Conditions?

INSERT INTO or UPDATE with Two Conditions

Problem Description:

The user encounters a time-consuming challenge: inserting a new row into a table if there isn't already a row matching two specific conditions ('name' and 'dates'), or updating the existing row if a match is found.

Solution:

The answer lies in MySQL's INSERT INTO ... ON DUPLICATE KEY UPDATE syntax. This powerful feature allows for efficient data manipulation by inserting a new row if no matching row exists or updating the existing row if a unique key constraint is violated.

To achieve the desired behavior, the table must have a unique key defined (a composite key in this case) for the two columns ('name' and 'dates'). This key serves as the identifier for unique rows in the table.

Example Scenario:

Consider the following table structure:

create table myThing (
    id int auto_increment primary key,
    name int not null,
    values1 int not null,
    values2 int not null,
    dates date not null,
    unique key(name,dates) -- This line is crucial
);

Inserting a new row with the following statement will either create a new row or update an existing one, depending on the existence of a row with the same 'name' and 'dates':

insert myThing(name,values1,values2,dates) values (777,1,1,'2015-07-11') on duplicate key update values2=values2 1;

Example Result:

select * from myThing;
 ---- ------ --------- --------- ------------ 
| id | name | values1 | values2 | dates      |
 ---- ------ --------- --------- ------------ 
| 1 | 777 | 1 | 4 | 2015-07-11 |
| 2 | 778 | 1 | 1 | 2015-07-11 |
 ---- ------ --------- --------- ------------ 

As the example demonstrates, the INSERT INTO ... ON DUPLICATE KEY UPDATE syntax efficiently handles both insert and update operations based on the defined unique key, eliminating the need for complex stored procedures.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3