在MySQL中更新2列的多行

时间:2012-02-19 17:24:59

标签: mysql sql case sql-update

跟进Update multiple rows in 1 column in MySQL

更新2列中多行的最有效查询是什么?

UPDATE example_table SET variable1 = 12 WHERE id=1;
UPDATE example_table SET variable2 = 'blue' WHERE id=1;

UPDATE example_table SET variable1 = 42 WHERE id=2;
UPDATE example_table SET variable2 = 'red' WHERE id=2;

UPDATE example_table SET variable1 = 32 WHERE id=3;
UPDATE example_table SET variable2 = 'yellow' WHERE id=3;

使用case似乎效率最高,但如果一次设置多个值,我该如何做呢?

4 个答案:

答案 0 :(得分:11)

如果你有一个名为categories的表,并说两列是display_ordertitle这就是你要做的:

UPDATE categories
SET display_order = CASE id
    WHEN 1 THEN 32
    WHEN 2 THEN 33
    WHEN 3 THEN 34
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)

答案 1 :(得分:2)

我认为CASE是解决方案。我们的想法是为每个变量使用单独的CASE语句。类似的东西:

UPDATE `example_table`
SET `variable1` = (CASE
    WHEN `id` = 1 THEN 12
    WHEN `id` = 2 THEN 42
    WHEN `id` = 3 THEN 32
    END),
`variable2` = (CASE
    WHEN `id` = 1 THEN 'blue'
    WHEN `id` = 2 THEN 'red'
    WHEN `id` = 3 THEN 'yellow'
    END);

希望它有所帮助!

答案 2 :(得分:2)

有些人不需要把这个Sign放在id''例如:'id'你可以把它留空......比如

UPDATE example_table
SET variable1 = (CASE
    WHEN id = 1 THEN 12

答案 3 :(得分:0)

这样的事情可能就是你想做的事情:

UPDATE example_table SET variable1 = 42,variable2 = 'red' WHERE id=2;