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

时间:2018-12-27 20:49:26

标签: postgresql postgresql-11

在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子句条目的引用无效

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

2 个答案:

答案 0 :(得分:3)

不要在“ 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

答案 1 :(得分:0)

您可以使用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