How to swap values of two rows in MySQL without violating unique constraint?

前端 未结 6 791
-上瘾入骨i
-上瘾入骨i 2020-12-01 07:29

I have a \"tasks\" table with a priority column, which has a unique constraint.

I\'m trying to swap the priority value of two rows, but I keep violating the constrai

6条回答
  •  孤城傲影
    2020-12-01 08:07

    you can achieve swapping your values with your above mentioned update statement, with a slight change in your key indexes.

    CREATE TABLE `tasks` (   `id` int(11) NOT NULL,   `name` varchar(200) DEFAULT NULL,   `priority` varchar(45) DEFAULT NULL,   PRIMARY KEY (`id`,`priority`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    This will have a primary key index as a combination of id and priority. you cna then swap values.

    UPDATE tasks 
    SET priority = 
    CASE
        WHEN priority=2 THEN 3 
        WHEN priority=3 THEN 2 
    END 
    
    WHERE priority IN (2,3);
    

    I dont see any need of user variables or temp variables here. Hope this solves your issue :)

提交回复
热议问题