我有一个名为 Users 的表。 我从其他表导入一些用户。 他们有一个 parent_id
我现在的 table
id,parent_id,imported_rows_id
1,1,NULL ->my old data has not last row value
2,1,Null ->my old data has not last row value
3,1,1100
4,1100,1101
5,1100,1102
6,1102,1103
现在我想将所有 parent_id 更改为 id where imported_rows_id = parent_id 和这里一样:
3,1,1100
4,3,1101
5,3,1102
6,5,1103
update users set parent_id = (select id from users where parent_id=imported_rows_id)
不允许同 table
真诚的
最佳答案
您可以通过自连接来实现:
update TableName t1 join
TableName t2 on t1.imported_rows_id=t2.parent_id
set t2.parent_id=t1.id
where t2.imported_rows_id is not null
结果:
id parent_id imported_rows_id
--------------------------------
1 1 (null)
2 1 (null)
3 1 1100
4 3 1101
5 3 1102
6 5 1103
结果为 SQL Fiddle
关于mysql - 将字段更新为同一个表中的其他字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31964087/