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

前端 未结 6 793
-上瘾入骨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:03

    Had a similar problem.

    I wanted to swap 2 id's that were unique AND was a FK from an other table.

    The fastest solution for me to swap two unique entries was:

    1. Create a ghost entry in my FK table.
    2. Go back to my table where I want to switch the id's.
    3. Turned of the FK Check SET FOREIGN_KEY_CHECKS=0;
    4. Set my first(A) id to the ghost(X) fk (free's A)
    5. Set my second (B) id to A (free's B)
    6. Set A to B (free's X)
    7. Delete ghost record and turn checks back on. SET FOREIGN_KEY_CHECKS=1;

提交回复
热议问题