开发者

ON DUPLICATE KEY UPDATE with WHERE condition

开发者 https://www.devze.com 2023-03-26 10:46 出处:网络
I update/insert values in a single table with the ON DUPLICATE KEY UPDATE function. So far everything is fine.

I update/insert values in a single table with the ON DUPLICATE KEY UPDATE function. So far everything is fine.

INSERT INTO table1 SET field1=aa, field2=bb, field3=cc
ON DUPLICATE KEY UPDATE SET field1=aa, field2=bb, fiel开发者_StackOverflow中文版d3=cc;

But now I would like to achieve that the update only is done if a condition (WHERE) is true.

Syntactically not correct:

INSERT INTO table1 SET field1=aa, field2=bb, field3=cc
ON DUPLICATE KEY UPDATE SET field1=aa, field2=bb, field3=cc WHERE field4=zz;

Any ideas how the correct SQL statement is?

Thanks a lot.


Using IF() should work, though it's not nice:

INSERT INTO table1 SET 
 field1=aa, 
 field2=bb, 
 field3=cc 
ON DUPLICATE KEY UPDATE SET 
 field1 = IF( field4 = zz, aa, field1 ),
 field2 = IF( field4 = zz, bb, field2 ),
 field3 = IF( field4 = zz, cc, field3 )

Only update the fields with new values if the condition is met, otherwise keep the old ones.

0

精彩评论

暂无评论...
验证码 换一张
取 消