mysql同时update多行

时间:2021-10-20 02:09:13
  1. 当我们只更新一个字段时的语法如下:

    UPDATE mytable
        SET myfield = CASE other_field
            WHEN 1 THEN 'value'
            WHEN 2 THEN 'value'
            WHEN 3 THEN 'value'
        END
    WHERE id IN (1,2,3)
  2. 当我们只更新多个字段时的语法如下:

    UPDATE categories
        SET display_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'
            WHEN 2 THEN 'New Title 2'
            WHEN 3 THEN 'New Title 3'
        END
    WHERE id IN (1,2,3)