【问题标题】:Postgresql: Updating with two inner joins [MySQL to PostgreSQL]Postgresql:使用两个内部连接进行更新 [MySQL 到 PostgreSQL]
【发布时间】:2018-12-27 20:49:26
【问题描述】:

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

【问题讨论】:

    标签: postgresql postgresql-11


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你可以用 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-24
        • 1970-01-01
        • 2020-11-29
        • 1970-01-01
        • 1970-01-01
        • 2012-07-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多