mysql - 将字段更新为同一个表中的其他字段

标签 mysql sql-update

我有一个名为 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/

相关文章:

mysql - Ruby #{} 插入换行符

php - 如何在 php 中使用 post 方法更新 mySQL 数据库

mysql - SQL 获取、编辑和更新数据

mysql - 根据 id 使用新列值更新整个列

php - 迁移两段代码,报错mysql_fetch_array() expects parameter 1 to be resource

mysql - Eloquent :在关系上调用Where

postgresql - 永远运行大量记录的功能

MYSQL UPDATE 未正确更新

sql - 将具有特定值的列更新为具有相同 id 的列值

python - 如何使用 mysql 连接器执行 .sql 文件并将其保存在 python 数据库中?