使用insert... on duplicate key update时,更新多列而不更新某些列的语法是什么?
我写了以下查询:
INSERT INTO table (id,number,text) VALUES (1,2,3),(3,5,"i want this remain the previous value and not change"),(1,2,3)
ON DUPLICATE KEY UPDATE id=VALUES(id), number=VALUES(number), text=VALUES(text);
如何更改某些值并让它们保留以前的值?
答案 0 :(得分:1)
使用IF
执行此操作:
INSERT INTO table (id,number,text) VALUES (1,2,3),(3,5,"ZZZ"),(1,2,3)
ON DUPLICATE KEY UPDATE id=VALUES(id), number=VALUES(number), text=IF(VALUES(text)="ZZZ", text, VALUES(text));
- 对于多个值,使用IN
代替=
:
INSERT INTO table (id,number,text) VALUES (1,2,3),(3,5,"ZZZ"),(1,2,"YYY")
ON DUPLICATE KEY UPDATE id=VALUES(id), number=VALUES(number), text=IF(VALUES(text) IN ("ZZZ", "YYY"), text, VALUES(text));