mysql what is the right syntax for this conditional update statement

你。 提交于 2019-12-11 01:15:03

问题


MYSQL, what I want is like

update tablename 

case fieldA

when value1 then set fieldX0=xxx,fieldX1=bbb,fieldX2=ccc ...

when value2 then set fieldY0=yyy,fieldY1=eee,fieldY2=fff ...

end

what is the right and simple syntax for it? thank you very much.


回答1:


It should be written this way:

UPDATE tablename
SET fieldX = CASE WHEN fieldA = 'value1' THEN 'xxx' ELSE fieldX END,
    fieldY = CASE WHEN fieldA = 'value2' THEN 'yyy' ELSE fieldY END
WHERE fieldA IN ('value1', 'value2'); 

Note that: I wrote the ELSE part this way, because the default for the ELSE is NULL if the condition of the CASE expression is not valid, so this will set it to the original value not to the NULL value.



来源:https://stackoverflow.com/questions/15740557/mysql-what-is-the-right-syntax-for-this-conditional-update-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!