Postgres - 如何在更新子查询中引用外表?

时间:2014-02-14 07:40:22

标签: sql postgresql

我正在尝试做以下事情:

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

即。根据空间查询设置表1中最近的城市..

但我无法引用我在子查询中更新的行。有什么方法吗?

2 个答案:

答案 0 :(得分:3)

这样的事情:

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

答案 1 :(得分:1)

如果你需要table1的1列更新table2的1列:

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