我有两个表,需要交换每个表中一列的值 - 当它们位于同一个表中时我可以执行此操作,但是当我尝试对不同的表执行此操作时,第二个值已被覆盖,因此得到丢失了。
例如:
table1
id user_id currency col2 col3......
1 1 10 Bob 2018-04-16
2 2 150 Tom 2018-05-17
3 3 60 Phil 2018-06-04
4 4 125 Jon 2017-12-01
5 5 35 Mike 2018-07-21
table2
id user_id salary col2 col3......
1 1 USD 16 Active
2 2 USD 17 Active
3 3 GBP 21 Left
4 4 CAD 16 Active
5 5 AUD 19 Active
我需要这些看起来像:
table1
id user_id currency col2 col3......
1 1 USD Bob 2018-04-16
2 2 USD Tom 2018-05-17
3 3 GBP Phil 2018-06-04
4 4 CAD Jon 2017-12-01
5 5 AUD Mike 2018-07-21
table2
id user_id salary col2 col3......
1 1 10 16 Active
2 2 150 17 Active
3 3 60 21 Left
4 4 125 16 Active
5 5 35 19 Active
我尝试过:
UPDATE table1 t1, table2 t2
SET t1.currency=t2.salary, t2.salary=t1.currency
WHERE t1.user_id=t2.user_id;
但这不起作用(货币设置正确,但工资设置不正确),可以吗?
Swap two columns values between two tables看起来像是一个可能的解决方案,但解决方案是更改表名称,因为所有列都需要交换,而我只需要交换单个列。
最佳答案
我相信您需要混合使用 DDL 和 DML 来完成此操作。
首先,您需要重命名要交换的列之一,并添加一列来保存新值:
alter table table1 change currency salary int;
alter table table1 add currency varchar(3) after salary;
然后独立更新每个表:
update table1 t1, table2 t2
set t1.currency = t2.salary
where t1.user_id = t2.user_id;
update table1 t1, table2 t2
set t2.salary = t1.salary
where t1.user_id = t2.user_id;
最后删除多余的列:
alter table table1 drop salary;
关于mysql - 在 2 个不同的表之间交换列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51641909/