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.
The above is the detailed content of How Can I Efficiently INSERT or UPDATE a MySQL Row Based on Two Conditions?. For more information, please follow other related articles on the PHP Chinese website!