Update Query based on condition

前端 未结 2 1976
谎友^
谎友^ 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:07
    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题