sql - PostgreSQL:基于连接列从另一个表更新目标表
问题描述
我需要使用 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
现在阶段 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。
感谢您对此的帮助
编辑
我尝试如下重写查询并且它有效。欢迎任何意见和建议。
解决方案
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
);
解决方案
假设它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;
我会说,根据样本数据和您想要做什么的描述找出正确的查询会简单得多。示例代码实际上并不是特别有用。
推荐阅读
- firebase - firebase 注销不适用于 FB 托管
- c# - EWS: BindToRecurringMaster 很慢,只需要经常性的master Id
- jquery - Jquery在提交表单时显示加载div(文件上传)
- python - 元类传递类名作为参数
- git - 如何挑选然后将分支标记为合并而无需添加到提交历史记录?
- javascript - 我可以告诉 nodeJs 服务器只生成动态 HTML(而 nginx 发送静态数据)然后自动发送到客户端吗?
- c++ - 使用 C++ 模板进行条件代码编译
- codeigniter-3 - Codeigniter base_url() 配置没有改变
- forms - 反应 react-jsonschema-form 更新状态
- java - Spring Batch Job 迁移到 Spring Boot 2 后停止运行