I would like to update multiple columns in my table using a case statement, but I cannot find how to do this (is this even possible). I came up with the following invalid reference query:
UPDATE tablename SET
CASE name
WHEN 'name1' THEN col1=5,col2=''
WHEN 'name2' THEN col1=3,col2='whatever'
ELSE col1=0,col2=''
END;
Is there any way of achieving the expected result with valid SQL?
If
name
has a unique index and your values are known to exist in the table, you can use this trick:If there are any additional
NOT NULL
columns without a default value, you'll have to add dummy values for those. Just leave them out of theON DUPLICATE KEY UPDATE
and they'll be ignored.I don't know of any clean way to do what you're asking. An equivalent valid SQL update would be:
Of course this isn't pretty and requires repeating the same cases (e.g.
'name1'
) multiple times, but I just don't think it's possible any other way.