MySQL CASE to update multiple columns

后端 未结 3 1063
走了就别回头了
走了就别回头了 2020-12-14 16:17

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 re

相关标签:
3条回答
  • 2020-12-14 16:56

    If name has a unique index and your values are known to exist in the table, you can use this trick:

    INSERT INTO tablename (name, col1, col2)
    VALUES ('name1', 5, '')
         , ('name2', 3, 'whatever')
    ON DUPLICATE KEY UPDATE
           col1 = VALUES(col1)
         , col2 = VALUES(col2);
    

    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 the ON DUPLICATE KEY UPDATE and they'll be ignored.

    0 讨论(0)
  • 2020-12-14 16:59

    I don't know of any clean way to do what you're asking. An equivalent valid SQL update would be:

    UPDATE tablename SET
        col1 = CASE name WHEN 'name1' THEN 5 WHEN 'name2' THEN 3 ELSE 0 END,
        col2 = CASE name WHEN 'name1' THEN '' WHEN 'name2' THEN 'whatever' ELSE '' END;
    

    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.

    0 讨论(0)
  • 2020-12-14 17:00
    UPDATE tablename
    SET col1 = CASE WHEN name = 'name1' THEN 5 
                    WHEN name = 'name2' THEN 3 
                    ELSE 0 
               END
     , col2 = CASE WHEN name = 'name1' THEN '' 
                   WHEN name = 'name2' THEN 'whatever' 
                   ELSE '' 
              END
    ;
    
    0 讨论(0)
提交回复
热议问题