【问题标题】:misunderstanding UPDATE FROM syntax对 UPDATE FROM 语法的误解
【发布时间】:2019-03-02 09:18:15
【问题描述】:

使用 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 语法时遗漏了什么?

【问题讨论】:

    标签: postgresql postgis spatial-query


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 2015-01-04
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多