使用另一个表中的值和SQLite中的where子句更新多行

时间:2014-06-23 11:49:50

标签: sql sqlite

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字段都设置为"我是一个"。

1 个答案:

答案 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