简体   繁体   English

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

[英]MYSQL UPDATE SET on the Same Column but with multiple WHERE Clauses

With MYSQL I'm using this query:使用 MYSQL 我使用这个查询:

UPDATE CustomerDetails_COPY
SET Category_ID = 10
WHERE Category_ID = 2

Thats fine but I'd like to ad 15+ more SET/WHERE to it like:没关系,但我想为它添加 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
.....

How would I add to this?我将如何添加到这个?

EDIT:编辑:

As Per Hunters Suggestion:根据猎人的建议:

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)

This works Great!这很好用! Thanks谢谢

Something like this should work for you:这样的事情应该适合你:

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)

Alternatively, as Simon suggested, you could do this to save from entering the values twice:或者,正如西蒙建议的那样,您可以这样做以防止两次输入值:

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

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

The typical way to do this would be这样做的典型方法是

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

Is there any reason you are avoiding this approach?你有什么理由避免这种方法吗?

Is there any correlation between the new and old values of category_ID? category_ID 的新旧值之间是否存在相关性?

you could create another table where the mapping is made.. like:您可以创建另一个表,其中进行映射.. 像:

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

then fill it in...然后填写...

then然后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM