1

在 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 中执行此查询的正确方法是什么?

4

2 回答 2

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

于 2018-12-27T21:34:38.597 回答
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<>小提琴演示

于 2018-12-27T21:26:19.227 回答