【发布时间】:2021-01-18 03:23:00
【问题描述】:
我需要使用 postreSQL 中 table2 的连接列从 table1 更新 table3,我可以想到一个通用的表表达式来实现它,但这似乎没有执行。
A>existing target data **table3**
col1 code uid
A 123 abc
B 123 cef
B>lookup table data **table2**
id uid
4 abc
5 cef
4 klm
5 mnp
C>new data in stage **table1**
col1 code uid
C 123 klm
D 123 mnp
D>result final target data **table3** (updated with table1)
col1 code uid
C 123 abc
D 123 def
解释:-
table3 中的 uid 在创建数据的 table2 中查找 加入后
code id col1
123 4 A
123 5 B
现在stage table1查找table2来创建join后的数据
code id col1
123 4 C
123 5 D
因此基于主键 code + id 然后 col1 的值更新为
col1 code uid
C 123 abc
D 123 def
试过的 SQL 代码
with
sm as
(
select
s.col1
,s.code
,ssi.id from stage.table3 s
join stage.table2 ssi on s.uid = ssi.uid ),
cte as (
select
k.col1
,k.code
,ss.id
from stage.table1 k
join stage.table2 ss on k.uid = ss.uid )
update sm set col1 = cte.col1
from cte where
cte.id = sm.id and cte.code = sm.code;
测试数据的 DDL
create table table3(col1, code, uid) as
(
select 'A',123,'abc'
union all
select 'B', 123,'cef'
);
create table table2(id,uid) as
(
select 4,'abc'
union all
select 5,'cef'
union all
select 4,'klm'
union all
select 5,'mnp'
);
create table table1(col1, code, uid) as
(
select 'C',123,'klm'
union all
select 'D',123,'mnp'
);
请注意:-目标table3没有id列,需要根据uid加入table2导出。
感谢您对此的帮助
编辑
我尝试如下重写查询并且它有效。欢迎任何cmets和建议。
解决方案
update table3 sm
set col1 = p.col1
from table1 p -- join stage table to lookup table to retrieve id
join table2 ss on p.uid = ss.uid
where exists
(select from table3 smi -- join target table to lookup table to retrieve id
join table2 ssi on smi.uid = ssi.uid
where -- filter and join both
ss.id = ssi.id and
sm.code = smi.code and
sm.uid = smi.uid and
sm.code = p.code
);
【问题讨论】:
-
编辑您的问题并提供示例数据、所需结果以及您想要完成的任务的清晰说明。
-
@GordonLinoff,尝试让问题更具描述性,这有意义吗?
-
我能够通过重新构建描述中提到的查询来获得解决方案
标签: sql postgresql sql-update inner-join