PostgreSQL - Using a Subquery to Update Multiple Column Values

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

    Using UPDATE FROM is a good solution when you don't have simple subselects. In this UPDATE I wanted to set the event_profile_id of the photos table to be the owner (event profiles are owners too) of the photo set the photo belongs to.

    UPDATE photos
    SET event_profile_id=photos_and_events.event_profile_id
    FROM (
      SELECT
        ph.id photo_id,
        pr.id event_profile_id
      FROM photos ph, profiles pr, photo_sets ps
      WHERE ph.main_photo_set_id=ps.id AND ps.owner_profile_id=pr.id
    ) AS photos_and_events
    WHERE photos.id=photos_and_events.photo_id;
    

提交回复
热议问题