Swapping Values in MySQL without Unique Constraint Violations
In MySQL, swapping values between two rows can be challenging when a unique constraint is applied to the affected column. The issue arises because MySQL enforces constraint checks after each row update, rather than the completion of the entire statement.
To address this limitation, consider the following solution:
<code class="sql">START TRANSACTION ; UPDATE tasks SET priority = CASE WHEN priority = 2 THEN -3 WHEN priority = 3 THEN -2 END WHERE priority IN (2,3) ; UPDATE tasks SET priority = - priority WHERE priority IN (-2,-3) ; COMMIT ;</code>
In this solution, a transaction is initiated to ensure that both updates are performed atomically. Negative values are temporarily assigned to the priorities to avoid conflicts with the unique constraint. Subsequently, another update assigns the negative values to the original priorities, effectively swapping their values.
Alternatively, if negative values are not permitted in the priority column, you can use temporary variables or create a temporary table to hold the swapped values. However, these methods may involve multiple queries.
It's important to note that removing the unique constraint temporarily is not recommended, as it can compromise data integrity.
The above is the detailed content of How to Swap Values in MySQL without Unique Constraint Violations?. For more information, please follow other related articles on the PHP Chinese website!