In MySql this is not easy to do, as it checks the unique constraints for every individual record during the update, not at the end (only).
So in order to allow the values of a column to be swapped, you need to allow the column to get a temporary value that will not conflict with any constraint. So if you have a column that has a foreign key constraint, and does not allow null
values either, it is going to be hard to find such a value in all possible cases.
For the following solution null
values must be allowed. If they currently are not, then first issue this statement to allow null
for the emp_id column:
alter table testing_table modify column emp_id int null;
Then:
start transaction;
update testing_table
set emp_id = null
where id = 1 and if(@emp1 := emp_id, 1, 1)
or id = 2 and if(@emp2 := emp_id, 1, 1);
update testing_table
set emp_id = if(id = 1, @emp2, @emp1)
where id in (1, 2);
commit;
SQL fiddle.
Explanation
This will first set the values to null
, while storing their previous values in @emp1
and @emp2
, and updates the same records with the values as retained in these variables, but swapped.
The if
s in the first update
statement are just there to make sure the assignment returns a true
expression and make the where
condition succeed. Note also that short-circuit evaluation will make sure that those assignments only happen when the left side of the and
operator evaluated to true
.