在单个查询中更新具有不同值的多个行 - MySQL

时间:2022-09-25 16:42:44

I'm new to MySQL.

我是MySQL的新手。

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

我在一个查询中使用它来更新具有不同值的多行:

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

I am using "WHERE" to improve performance (without it every row in the table would be tested).

我正在使用“WHERE”来提高性能(没有它会测试表中的每一行)。

But what if I have this senario (when I don't want to update title for id 2 and 3):

但是,如果我有这个senario(当我不想更新id 2和3的标题时):

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'
    END
WHERE id IN (1,2,3)

The above code will change the title for id 2 and 3 into "NULL"...

上面的代码会将id 2和3的标题更改为“NULL”...

What is the right way to make the query, but skip updating title for id 2 and 3 and still keep the performance "WHERE id IN" gives ?

进行查询的正确方法是什么,但跳过更新id 2和3的标题仍然保持性能“WHERE id IN”给出?

Maybe like this

也许是这样的

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'
        WHEN  THEN 
        WHEN  THEN 
    END
WHERE id IN (1,2,3)

2 个解决方案

#1


12  

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)

#2


0  

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

#1


12  

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)

#2


0  

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