Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL conditionally UPDATE rows' boolean column values based on a whitelist of ids

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 given POST will have the page's worth of IDs with a true or false value.

I was trying to go this direction:

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

But this resulted in the "true id" rows being updated to true, and ALL other rows were updated to false.

I assume I've made some gross syntactical error, or perhaps that I'm approaching this incorrectly.

Any thoughts on a solution?

like image 333
Dan Lugg Avatar asked Aug 07 '11 20:08

Dan Lugg


2 Answers

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)
like image 173
Icarus Avatar answered Nov 07 '22 10:11

Icarus


You can avoid field = field

update my_table
    set field = case
        when id in (....) then true
        when id in (...) then false
        else field
    end
like image 34
Nicola Cossu Avatar answered Nov 07 '22 10:11

Nicola Cossu