Postgresql:使用两个内部连接更新 [MySQL 到 PostgreSQL]

Postgresql: Updating with two inner joins [MySQL to 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

我收到以下错误:

ERROR: invalid reference to FROM-clause entry for table "a"

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

您可以使用 CTE 重写它:

WITH cte AS (
  SELECT c.*, b.field_five
  FROM table_b B  
  JOIN table_c C 
    ON B.agency_id = C.agency_id
)
UPDATE table_a A 
SET field_three = C.field_four
FROM cte c
WHERE A.field_five = c.field_five
  AND A.field_two = c.field_two;

db<>fiddle demo

不要在 "set" 中指定要更新的 table 并将 "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