PostgreSQL - Using a Subquery to Update Multiple Column Values

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

    I needed to do multiple inserts on a table taking the data from two tables without common columns between them and ignoring records already present.

    The following sql was tested on Postgresql 11, althought it should work fine on v9+:

    WITH permission_info AS (
        SELECT id
        FROM permission
        WHERE permission."key" LIKE 'prefix_for_admin_%'
    ), role_info AS (
        SELECT id 
        FROM role
        WHERE role."name" = 'Admin'
    )
    INSERT INTO role_permission_table
    (
        role_id,
        permission_id
    )
        SELECT role_info.id, permission_info.id FROM role_info, permission_info
    
    ON CONFLICT DO NOTHING
    ;
    

提交回复
热议问题