簡體   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