更新存在的地方删除不存在的行
Update where exists delete row where doesn't
我可以更新,也可以删除,但我想同时进行。
我有一个这样的table ORIG,列名是
ref,fname,lname,add1,add2,add3,add4
A1 a b c d h j
S2 f d s e y t
B3 j f s e o p
第一列是唯一的
然后另一个 table 像这样的数据
ref,fname,lname,add1,add2
A1 b c d e
B3 k g h t
我想使用第二个 table 更新第一个 table 并删除任何不具有唯一性的行
因此最终结果需要是 table ORIG,如下所示
A1 b c d e h j
B3 k g h t o p
我能一次性完成吗?
您可以为此使用相关子查询:
delete
from orig o
where not exists (
select 1
from data d
where d.col1 = o.col1
)
我可能会使用 CTE 来解决这个问题:
with u as (
update orig
set b = d.b, . . .
from data d
where d.a = orig.a
returning *
)
delete from orig
where not exists (select 1 from u where u.a = d.a);
第一个 CTE 更新行。第二个执行删除。
我可以更新,也可以删除,但我想同时进行。
我有一个这样的table ORIG,列名是
ref,fname,lname,add1,add2,add3,add4
A1 a b c d h j
S2 f d s e y t
B3 j f s e o p
第一列是唯一的
然后另一个 table 像这样的数据
ref,fname,lname,add1,add2
A1 b c d e
B3 k g h t
我想使用第二个 table 更新第一个 table 并删除任何不具有唯一性的行
因此最终结果需要是 table ORIG,如下所示
A1 b c d e h j
B3 k g h t o p
我能一次性完成吗?
您可以为此使用相关子查询:
delete
from orig o
where not exists (
select 1
from data d
where d.col1 = o.col1
)
我可能会使用 CTE 来解决这个问题:
with u as (
update orig
set b = d.b, . . .
from data d
where d.a = orig.a
returning *
)
delete from orig
where not exists (select 1 from u where u.a = d.a);
第一个 CTE 更新行。第二个执行删除。