首页 > 解决方案 > Postgresql:使用两个内部连接进行更新 [MySQL 到 PostgreSQL]

问题描述

在 MySQL 中,可以这样做:

update 
    table_a A 
inner join 
    table_b B 
on 
    A.field_five = B.field_five
inner join 
    table_c C 
on 
    B.field_one = C.field_one and A.field_two = C.field_two
set A.field_three = C.field_four

我试图在 PostgreSQL 中构造相同的查询,如下所示:

update table_a A 
    set A.field_three = C.field_four
from table_b B  
    inner join table_c C 
on 
    B.agency_id = C.agency_id and A.field_two = C.field_two
where 
    A.field_five = B.field_five

我收到以下错误:

错误:对表“a”的 FROM 子句条目的引用无效

我正在使用 PostgreSQL 11。在 postgres 中执行此查询的正确方法是什么?

标签: postgresqlpostgresql-11

解决方案


不要在“set”中指定要更新的表,并将“A.field_two = C.field_two”移动到 where 子句

update table_a A
    set field_three = C.field_four
from table_b B  
    inner join table_c C 
on 
    B.agency_id = C.agency_id 
where 
    A.field_five = B.field_five
    and A.field_two = C.field_two

https://www.db-fiddle.com/f/mipu88sd4JDar25TtvQCQJ/1


推荐阅读