Is there a query with which i can exchange the values of two rows with single query?
Asked
Active
Viewed 1.7k times
2 Answers
27
you can see the solution in this article
http://www.microshell.com/database/sql/swap-values-in-2-rows-sql/
look at the : The elegant way , make a join to get the data from the 2 rows to be swapped in 1 row, after that make an update is easy.
example :
UPDATE
rules AS rule1
JOIN rules AS rule2 ON
( rule1.rule_id = 1 AND rule2.rule_id = 4 )
SET
rule1.priority = rule2.priority,
rule2.priority = rule1.priority
;

Haim Evgi
- 123,187
- 45
- 217
- 223
-
What if you want to swap the last 2 rows ? – Alucard Jul 21 '14 at 15:31
9
UPDATE my_table SET a=@tmp:=a, a=b, b=@tmp;

Juan Mellado
- 14,973
- 5
- 47
- 54

Rajaa
- 107
- 1
- 2
-
1Your solution is for swapping two columns, the question was about swapping two rows. – redux Dec 05 '14 at 10:28
-
1
-