将 select 转换为 Update with multiple joins Postgres

Turn select into Update with multiple joins Postgres

所以这是我第一次想对具有多个连接的查询进行更新。

数据库 = Postgres v.10

这是我到目前为止尝试过的:

update table1 t1 set t4.datum = t1.datum
from table1 t1
inner join table3 t3 on t3.id = t1.id
inner join table4 t4 on t4.id = t3.t4_id
where t3.id = 550 and t4.scale is not null and t4.datum is null

错误:SQL错误[42712]:错误:table多次指定名称“t1”

下次尝试:

update table1 t1 set t4.datum = t.datum
from table1 t
inner join table3 t3 on t3.id = t.id
inner join table4 t4 on t4.id = t3.t4_id
where t3.id = 550 and t4.scale is not null and t4.datum is null

错误:SQL错误[42703]:错误:关系“table1”的列“t4”不存在 排名:28

最后一次尝试:

update table1 t1 set t4.datum = t.datum
from table1 t
inner join table3 t3 on t3.id = t.id
inner join table4 t4 on t4.id = t3.t4_id
where t1.id = t.id and t3.id = 550 and t4.scale is not null and t4.datum is null

错误:SQL错误[42703]:错误:关系“table1”的列“t4”不存在 排名:28

我做错了什么?

在 FROM 子句中引用 table 的别名,然后在整个过程中使用它。我认为我正确地编辑了这个:

update t1 set t4.datum = t1.datum
from table1 t1
inner join table3 t3 on t3.id = t1.id
inner join table4 t4 on t4.id = t3.t4_id
where t3.id = 550 and t4.scale is not null and t4.datum is null;

我认为你的问题是因为想从 table table1.

更新 t4.datum

您应该将集合列 t4.datum = t1.datum 更改为 t1.datum = t4.datum 因为您想要更新 table1(更新查询:update table1 t1)并且 t4.datum 不引用 table1

应该像下面这样更改查询(如果你想更新 table1):

update table1 t1 set t1.datum = t4.datum
from table1 t
inner join table3 t3 on t3.id = t.id
inner join table4 t4 on t4.id = t3.t4_id
where t1.id = t.id and t3.id = 550 and t4.scale is not null and t4.datum is null

已编辑

查询更新 table4:

update table4 u_t4 set datum = t1.datum
from table1 t1
inner join table3 t3 on t3.id = t1.id
inner join table4 t4 on t4.id = t3.t4_id
where t4.id = u_t4.id and t3.id = 550 and t4.scale is not null and t4.datum is null

您不应在 FROM 子句中重复更新的目标 table。所以像。分配 set t4.datum = t.datum 似乎也是错误的。如果要更新 table1,则不能在作业的左侧引用 t4。此外,目标列不能在 SET 部分内是“table 限定的”(因为很清楚 table 的列是指哪个)

所以我认为您正在寻找这样的东西:

update table1 t1 
   set datum = t4.datum
from table3 t3 
  inner join table4 t4 on t4.id = t3.t4_id
where t1.id = t3.id 
  and t3.id = 550 
  and t4.scale is not null 
  and t4.datum is null