简体   繁体   中英

Postgres - How to reference outer table in update subquery?

I'm trying to do something like the following:

UPDATE table1
SET table1.nearest_city_id = subquery.id
FROM 
  (SELECT id FROM cities ORDER BY cities.location <-> table1.location LIMIT 1)
  AS subquery;

ie set the nearest city in table 1 based on a spatial query..

But I can't reference the row I'm updating within the subquery. Any way around this?

Something like this:

UPDATE table1
  SET nearest_city_id = (select id
                         from cities c
                         ORDER BY c.location <-> table1.location
                         LIMIT 1);

If you need update 1 column of table1 by 1 column of table2 by one condition :

UPDATE Table1 
 SET Table1.Column = A.Column 
      FROM(SELECT Column,Id FROM Table2) As A
 WHERE Table1.Id=Table2.Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM