Update Query based on condition

前端 未结 2 1975
谎友^
谎友^ 2021-01-18 09:40

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 field         


        
2条回答
  •  借酒劲吻你
    2021-01-18 10:09

    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.

提交回复
热议问题