【问题标题】:Turn select into Update with multiple joins Postgres使用多个连接将选择变成更新 Postgres
【发布时间】:2022-01-07 04:40:59
【问题描述】:

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

数据库 = 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]:错误:表名“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

我做错了什么?

【问题讨论】:

    标签: postgresql join


    【解决方案1】:

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

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

    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
    

    【讨论】:

      【解决方案2】:

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

      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;
      

      【讨论】:

      • 不起作用:(
      【解决方案3】:

      我认为您的问题是因为想从表 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
      

      【讨论】:

      • 是的,我在表格上犯了一个错误。实际上我想更新 table4,因为 t4.datum 在那个表中
      • 我编辑了更新table4的帖子
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 2017-10-27
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多