MYSQL UPDATE SET在同一列上但具有多个WHERE子句

时间:2012-02-20 21:14:59

标签: mysql

使用MYSQL我正在使用此查询:

UPDATE CustomerDetails_COPY
SET Category_ID = 10
WHERE Category_ID = 2

多数民众赞成可以,但我希望再加上15 {}以上SET/WHERE

UPDATE CustomerDetails_COPY
SET Category_ID = 9  WHERE Category_ID = 3
SET Category_ID = 12 WHERE Category_ID = 4
SET Category_ID = 11 WHERE Category_ID = 5
.....

我该如何添加?

编辑:

按照猎人的建议:

UPDATE CustomerDetails_COPY
    SET Category_ID = CASE Category_ID
        WHEN 2 THEN 10 
        WHEN 3 THEN 9
        WHEN 4 THEN 12
        WHEN 5 THEN 11
    END
WHERE Category_ID IN (2,3,4,5)

这很棒!感谢

3 个答案:

答案 0 :(得分:18)

这样的事情对你有用:

UPDATE CustomerDetails_COPY
    SET Category_ID = CASE Category_ID
        WHEN 2 THEN 10 
        WHEN 3 THEN 9
        WHEN 4 THEN 12
        WHEN 5 THEN 11
    END
WHERE Category_ID IN (2,3,4,5)

或者,正如Simon建议的那样,你可以这样做以避免两次输入值:

UPDATE CustomerDetails_COPY
    SET Category_ID = CASE Category_ID
        WHEN 2 THEN 10 
        WHEN 3 THEN 9
        WHEN 4 THEN 12
        WHEN 5 THEN 11
        ELSE Category_ID
    END

来源:http://www.karlrixon.co.uk/writing/update-multiple-rows-with-different-values-and-a-single-sql-query/

答案 1 :(得分:2)

执行此操作的典型方法是

UPDATE CustomerDetails_COPY SET Category_ID = 10 WHERE Category_ID = 2
UPDATE CustomerDetails_COPY SET Category_ID = 9  WHERE Category_ID = 3
UPDATE CustomerDetails_COPY SET Category_ID = 12 WHERE Category_ID = 4
UPDATE CustomerDetails_COPY SET Category_ID = 11 WHERE Category_ID = 5

你有没有理由不采用这种方法?

category_ID的新旧值之间是否存在任何关联?

答案 2 :(得分:1)

您可以创建另一个映射的表格,如:

map_table
-----------
mani_id
new_id

然后填写...

然后

UPDATE CustomerDetails_Copy set category_id = (select new_id from map_table where mani_id = category_id )