Pregunta

When using insert... on duplicate key update, what is the syntax to update multiple columns and not update some columns?

i wrote the following query:

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);

how to not change some values and let them remain it's previous value?

¿Fue útil?

Solución

Do it with 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));

-for multiple values use IN instead of =:

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));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top