繁体   English   中英

PostgreSQL:根据连接列从另一个表更新目标表

[英]PostgreSQL : Update Target table from another table based on a joined column

我需要在 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

解释:-

在 table2 中查找 table3 中的 uid,它在 join 后创建数据为

code id col1
123  4  A
123  5  B

现在阶段 table1 在 table2 中查找以在 join 后创建数据

code id col1
123  4  C
123  5  D

因此基于主键代码 + 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 来派生。

感谢您对此的帮助

编辑

我尝试按如下方式重写查询并且它有效。 欢迎任何意见和建议。

解决方案

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
);

我认为你想要的逻辑是:

update table3 t3
set col1 = t1.col1
from table1 t1
inner join table2 t2 on t2.uid = t1.uid
where t3.id = t2.id

假设table2.id是唯一的或者是主键,那么我认为逻辑是:

update stage.table3 s 
    set s.col1 = 
    from stage.table2 ssi join
         stage.table1 k
         on k.uid = ss.uid 
    where s.uid = ssi.uid;

我会说根据示例数据和您想要做什么的描述找出正确的查询会简单得多。 示例代码实际上并不是特别有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM