Update Query based on condition

不问归期 提交于 2019-12-01 20:26:28

问题


I would like to do the following. Update a field based on the value of another field like

update table set if(fielda=1){fieldb=2 fieldc=3}else{fieldd=2 fielde=3}

I know this is not valid mysql but its the best way for me to describe the problem.


回答1:


update table set
b = case when a = 1 then 2 else b end,
c = case when a = 1 then 3 else c end,
d = case when a = 1 then d else 2 end,
e = case when a = 1 then e else 3 end

edit

according to your comment try this:

update table set
datefield_a = case when field_a = 1 then now() else datefield_a end,
datefield_b = case when field_a <> 1 then now() else datefield_b end



回答2:


I think this syntax will achieve the result you attempted to specify.

UPDATE mytable
   SET fieldb = CASE WHEN fielda = 1 THEN 2 ELSE fieldb END
     , fieldc = CASE WHEN fielda = 1 THEN 3 ELSE fieldc END
     , fieldd = CASE WHEN fielda = 1 THEN fieldd ELSE 2 END
     , fielde = CASE WHEN fielda = 1 THEN fielde ELSE 3 END

The "trick" here is that we are updating all four columns, but in some "cases", we are assigning the current value of the column back to the column, resulting in no real change to the column value. (Once you get your mind bent around that idea, it's pretty easy.)

With MySQL, we do have a handy IF function (not available in most other RDBMS) that we can use to abbreviate that a bit, and achieve the same thing:

UPDATE mytable
   SET fieldb = IF(fielda = 1, 2, fieldb)
     , fieldc = IF(fielda = 1, 3, fieldc)
     , fieldd = IF(fielda = 1, fieldd, 2)
     , fielde = IF(fielda = 1, fielde, 3)

The pain is that you still have to repeat that same conditional test multiple times.

A single scan through the table (like these statements do), and getting all those assignments done in one fell swoop is going to be faster (and more efficient) than breaking this up and doing the assignments piecemeal using multiple statements.



来源:https://stackoverflow.com/questions/11478375/update-query-based-on-condition

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