PK | PARENT | COMMENT
---+--------+-----------
1 | | I AM ONE
2 | | I AM TWO
3 | 1 | I AM ONE
4 | 1 |
5 | 2 | I AM TWO
6 | 2 | I AM THREE
我想更新COMMENT
不为空的行的PARENT
字段,以便COMMENT
与父代相同。这是预期的结果:
PK | PARENT | COMMENT
---+--------+---------
1 | | I AM ONE
2 | | I AM TWO
3 | 1 | I AM ONE
4 | 1 | I AM ONE
5 | 2 | I AM TWO
6 | 2 | I AM TWO
我已尝试过此查询:
UPDATE MYTABLE
SET COMMENT =
(
select table2.COMMENT
from MYTABLE as table1
join MYTABLE as table2
on (table1.PARENT = table2.PK)
where table1.PARENT is not null
)
where PK in
(
select table1.PK
from MYTABLE as table1
left outer join MYTABLE as table2
on (table1.PARENT = table2.PK)
where table1.PARENT is not null
)
但这会导致非空COMMENT
行的所有PARENT
字段都设置为"我是一个"。
答案 0 :(得分:4)
要更新Parent
不为NULL的行,请使用如下语句:
UPDATE MyTable
SET ...
WHERE Parent IS NOT NULL
要查找父评论,只需使用相关子查询(需要引用UPDATE语句中的表,否则它不知道哪一行是当前正在更新的行):
UPDATE MyTable
SET Comment = (SELECT Comment
FROM MyTable AS MyParent
WHERE MyParent.PK = MyTable.Parent)
WHERE Parent IS NOT NULL