【问题标题】:PostgreSQL : Update Target table from another table based on a joined columnPostgreSQL:基于连接列从另一个表更新目标表
【发布时间】: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


【解决方案1】:

我认为你想要的逻辑是:

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

【讨论】:

  • 感谢回复,但是table3没有id列,必须从table2加入,是否可以容纳或者我错过了什么
【解决方案2】:

假设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;

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

【讨论】:

  • 添加了解释和想要的结果
猜你喜欢
  • 1970-01-01
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
相关资源
最近更新 更多