MySQL update conditions in one query (UPDATE, SET & CASE)

前端 未结 2 1536
无人及你
无人及你 2020-12-15 06:25

I\'m trying to update a set of records (boolean fields) in a single query if possible.

The input is coming from paginated radio controls, so a

相关标签:
2条回答
  • 2020-12-15 07:01

    You can avoid field = field

    update my_table
        set field = case
            when id in (....) then true
            when id in (...) then false
            else field
        end
    
    0 讨论(0)
  • 2020-12-15 07:04

    Didn't you forget to do an "ELSE" in the case statement?

    UPDATE my_table
        SET field = CASE
            WHEN id IN (/* true ids */) THEN TRUE
            WHEN id IN (/* false ids */) THEN FALSE
            ELSE field=field 
        END
    

    Without the ELSE, I assume the evaluation chain stops at the last WHEN and executes that update. Also, you are not limiting the rows that you are trying to update; if you don't do the ELSE you should at least tell the update to only update the rows you want and not all the rows (as you are doing). Look at the WHERE clause below:

      UPDATE my_table
            SET field = CASE
                WHEN id IN (/* true ids */) THEN TRUE
                WHEN id IN (/* false ids */) THEN FALSE
            END
      WHERE id in (true ids + false_ids)
    
    0 讨论(0)
提交回复
热议问题