小编典典

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

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)

这很棒!谢谢


阅读 1009

收藏
2020-05-17

共1个答案

小编典典

这样的事情应该为您工作:

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/

2020-05-17