Update multiple rows with different values in a single query - MySQL

后端 未结 2 1797
长情又很酷
长情又很酷 2020-12-30 10:04

I\'m new to MySQL.

I\'m using this to update multiple rows with different values, in a single query:

UPDATE categories
    SET order         


        
相关标签:
2条回答
  • 2020-12-30 10:50

    Set title equal to itself when you don't want to update it to a different value.

    UPDATE categories
        SET order = CASE id
            WHEN 1 THEN 3
            WHEN 2 THEN 4
            WHEN 3 THEN 5
        END,
        title = CASE id
            WHEN 1 THEN 'New Title 1'
            ELSE title
        END
    WHERE id IN (1,2,3)
    
    0 讨论(0)
  • 2020-12-30 10:50
    UPDATE `table_name` SET `field_name1` = CASE `id`
    WHEN '1' THEN 'value_1'
    WHEN '2' THEN 'value_2'
    WHEN '3' THEN 'value_3'
    ELSE `field_name1`
    END,
    `field_name2`= CASE id
    WHEN '1' THEN 'value_1'
    WHEN '2' THEN 'value_2'
    WHEN '3' THEN 'value_3'
    ELSE `field_name2`
    END
    
    0 讨论(0)
提交回复
热议问题