如何使用sql更新列两次

时间:2017-06-16 09:31:03

标签: mysql sql

我有一张包含这些值的表格:

Name       |  id
----------------
Blue guy   |  20
Green girl |  10

id列是唯一值。我想要的是将blue guy id更新为10,并在同一查询中我想将绿色女孩ID更新为20.我当前的SQL查询是:

UPDATE colorpeople SET id = 20
WHERE name = 'Blue guy';

我可以在哪里指定更新绿色女孩?

5 个答案:

答案 0 :(得分:4)

试试这个:

UPDATE colorpeople 
SET id = (case 
           when name = 'Blue guy' then 10   
           when name = 'Green girl' then 20 
           else id = id 
           end)

答案 1 :(得分:1)

请尝试以下脚本:

ALTER TABLE colorpeople DROP CONSTRAINT PK_colorpeople

UPDATE colorpeople SET ID = 10 WHERE Name = 'Blue guy'
UPDATE colorpeople SET ID = 20 WHERE Name = 'Green girl'

ALTER TABLE colorpeople ADD CONSTRAINT PK_colorpeople PRIMARY KEY /* CLUSTERED */ (ID)

答案 2 :(得分:0)

你应该尝试这样的事情:

INSERT INTO colorpeople id VALUES 10, 20
ON DUPLICATE KEY UPDATE id=VALUES(id);

答案 3 :(得分:0)

执行此操作的最佳方法是使用WHERE子句:

UPDATE colorpeople 
    SET id = (case when name = 'Blue guy' then 10
                   when name = 'Green girl' then 20
              end)
    WHERE name in ('Blue guy', 'Green girl');

答案 4 :(得分:-1)

如果您想更新已存在的唯一键

UPDATE colorpeople SET id = -20 WHERE naam = 'Blue guy';
UPDATE colorpeople SET id = -10 WHERE naam = 'Green girl';
UPDATE colorpeople SET id = -id WHERE naam in ('Blue guy', 'Green girl');