PostgreSQL - Using a Subquery to Update Multiple Column Values

后端 未结 7 1062
无人共我
无人共我 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:10

    One option (but not the only one) is to use two separate sub-queries:

    update table1
    set col1 = (select min(ship_charge) from orders),
        col2 = (select max(ship_charge) from orders)
    where col4 = 1001;
    

    From the fine manual for PostgreSQL 9.0's UPDATE:

    According to the standard, the column-list syntax should allow a list of columns to be assigned from a single row-valued expression, such as a sub-select:

    UPDATE accounts SET (contact_last_name, contact_first_name) =
    (SELECT last_name, first_name FROM salesmen
     WHERE salesmen.id = accounts.sales_id);
    

    This is not currently implemented — the source must be a list of independent expressions.

提交回复
热议问题