I have 2 columns where there's a number in them if column 1 has a larger number than column 2 I want to swap the values between these 2 columns.
Is there an easy way to do this with a query?
start:
id | column 1 | column 2
------------------------
1 50 3
2 51 4
finish:
id | column 1 | column 2
------------------------
1 3 50
2 4 51
You can't just swap values. You need temporary variable First way:
UPDATE table_name SET column1=column2, column2=@temp WHERE (@temp:=column1) > column2;
Second way: This way is better because it check is any value is NULL
UPDATE table_name SET column1=(@temp:=column1), column1= column2, column2 = @temp WHERE column1 > column2;
Second way is simple. It compare two cols and swap this cols if needs.
In an UPDATE
statement MySql uses non standard SQL behavior when it comes to the use of values of the updated columns, because in a statement like this:
SET a = x, b = a
the value of a
in the assignment b = a
will not be the original value that is stored in the table, but the value of a
after the assignment a = x
.
So this:
update tablename
set column1 = column2,
column2 = column1
that would work in other databases does not work in MySql.
There is a workaround that does not use variables or unnecessary joins:
update tablename
set column1 = column1 + column2,
column2 = column1 - column2,
column1 = column1 - column2
where column1 > column2;
which works since:
Single-table UPDATE assignments are generally evaluated from left to right.
(from 13.2.13 UPDATE Statement )
See the demo .
Results:
| id | column1 | column2 |
| --- | ------- | ------- |
| 1 | 3 | 50 |
| 2 | 4 | 51 |
You have a primary key on the table, so a simple option is join
:
update t join
t t2
on t.id = t2.id
set t.x = t2.y,
t.y = t2.x
where t.x > t.y;
Here is a db<>fiddle.
I prefer this method to using variables for several reasons:
set
clauses, which I don't think that MySQL guarantees.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.