updating table rows in postgres using subquery

前端 未结 6 1188
北荒
北荒 2020-11-27 08:42

Using postgres 8.4, My goal is to update existing table:

CREATE TABLE public.dummy
(
  address_id SERIAL,
  addr1 character(40),
  addr2 character(40),
  ci         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 09:25

    There are many ways to update the rows.

    When it comes to UPDATE the rows using subqueries, you can use any of these approaches.

    1. Approach-1 [Using direct table reference]
    UPDATE
      
    SET
      customer=.customer,
      address=.address,
      partn=.partn
    FROM
      
    WHERE
      .address_id=.address_i;
    

    Explanation: table1 is the table which we want to update, table2 is the table, from which we'll get the value to be replaced/updated. We are using FROM clause, to fetch the table2's data. WHERE clause will help to set the proper data mapping.

    1. Approach-2 [Using SubQueries]
    UPDATE
      
    SET
      customer=subquery.customer,
      address=subquery.address,
      partn=subquery.partn
    FROM
      (
        SELECT
          address_id, customer, address, partn
        FROM  /* big hairy SQL */ ...
      ) AS subquery
    WHERE
      dummy.address_id=subquery.address_id;
    

    Explanation: Here we are using subquerie inside the FROM clause, and giving an alias to it. So that it will act like the table.

    1. Approach-3 [Using multiple Joined tables]
    UPDATE
      
    SET
      customer=.customer,
      address=.address,
      partn=.partn
    FROM
       as t2
      JOIN  as t3
      ON
        t2.id = t3.id
    WHERE
      .address_id=.address_i;
    

    Explanation: Sometimes we face the situation in that table join is so important to get proper data for the update. To do so, Postgres allows us to Join multiple tables inside the FROM clause.

    1. Approach-4 [Using WITH statement]

      • 4.1 [Using simple query]
    WITH subquery AS (
        SELECT
          address_id,
          customer,
          address,
          partn
        FROM
          ;
    )
    UPDATE 
    SET customer = subquery.customer,
        address  = subquery.address,
        partn    = subquery.partn
    FROM subquery
    WHERE .address_id = subquery.address_id;
    
    • 4.2 [Using query with complex JOIN]
    WITH subquery AS (
        SELECT address_id, customer, address, partn
        FROM
           as t1
        JOIN
           as t2
        ON
          t1.id = t2.id;
        -- You can build as COMPLEX as this query as per your need.
    )
    UPDATE 
    SET customer = subquery.customer,
        address  = subquery.address,
        partn    = subquery.partn
    FROM subquery
    WHERE .address_id = subquery.address_id;
    

    Explanation: From Postgres 9.1, this(WITH) concept has been introduces. Using that We can make any complex queries and generate desire result. Here we are using this approach to update the table.

    I hope, this would be helpful.

提交回复
热议问题