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.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3