将字段更新为同一 table 中的其他字段
update a field to other field in same table
我有一个名为 table 的用户。
我从其他 table 导入了一些用户。
他们有 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
我有一个名为 table 的用户。 我从其他 table 导入了一些用户。 他们有 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