误解UPDATE FROM语法

时间:2018-09-26 14:39:42

标签: postgresql postgis spatial-query

使用PostGIS,我有两个表,第一个表包含250个城市的边界,第二个表包含世界上所有国家的边界​​。

我试图影响它所属国家的每个城市。以下查询可让我获得所需的结果。

SELECT DISTINCT ON (cities.id) cities.id, country.id
FROM cities
LEFT JOIN country ON st_intersects(country.geom, cities.geom)

但是当我使用此查询时:

UPDATE cities
SET country_id=subq.id
FROM (SELECT DISTINCT ON (cities.id) country.id
    FROM cities
    LEFT JOIN country ON st_intersects(country.geom, cities.geom)) AS subq

country_id列充满了相同的编号。

在使用UPDATE FROM语法时我错过了什么?

1 个答案:

答案 0 :(得分:2)

您需要将两个查询与一个联接条件相关联:

UPDATE cities
  SET country_id=subq.id
FROM (
  SELECT DISTINCT ON (cities.id) country.id
  FROM cities
    LEFT JOIN country ON st_intersects(country.geom, cities.geom)
) AS subq
  where subq.id = cities.id;

但是我认为您不需要子选择。您可以将国家/地区表直接加入城市表:

UPDATE cities
  SET country_id = country.id
FROM country 
where st_intersects(country.geom, cities.geom)