PostgreSQL - Using a Subquery to Update Multiple Column Values

后端 未结 7 958
无人共我
无人共我 2021-02-02 08:01

I need to be able to update multiple columns on a table using the result of a subquery. A simple example will look like below -

UPDATE table1
SET (col1, col2) =         


        
7条回答
  •  春和景丽
    2021-02-02 08:13

    If you want to avoid two subselects, the query can be rewritten like this:

    UPDATE table1
      SET col1 = o_min, col2 = o_max
    FROM ( 
        SELECT min(ship_charge) as o_min, 
               max(ship_charge) as o_max
        FROM orders
    ) t 
    WHERE col4 = 1001
    

    If ship_charge is not indexed, this should be faster than two subselects. If ship_charge is indexed, it probably doesn't make a big difference


    Edit

    Starting with Postgres 9.5 this can also be written as:

    UPDATE table1
      SET (col1, col2) = (SELECT min(ship_charge), max(ship_charge) FROM orders)
    WHERE col4 = 1001
    

提交回复
热议问题