使用位于多边形内的点更新数据库行


10

我有一个PostGIS / Postgresql数据库,其中有两个表。一个具有点几何,另一个将国家边界表示为多边形。我想将每个点相交的国家/地区名称添加到我的点表中的每一行。也许是一大更新查询。我认为可以使用直接SQL来做到这一点,但我不知道从哪里开始。任何对此的建议将不胜感激...

Answers:


9

无需功能的另一种选择

update points set country = t1.country from 
(
    select points.oid, countries.name as country from
    countries INNER JOIN points on st_contains(countries.wkb_geometry,points.wkb_geometry)
) t1 
where t1.oid = points.oid

我怀疑(尽管我没有测试过)这会比使用您的示例中的嵌套函数更快。

我的运行输出说明(希望您的外观相似)。如果您有更多的Seq扫描结果,那就需要看一下,也许索引设置不正确。

Update on points  (cost=1.18..29.40 rows=121 width=129)"
  ->  Nested Loop  (cost=1.18..29.40 rows=121 width=129)"
        Join Filter: _st_contains(countries.geometry, public.points.geometry)"
        ->  Hash Join  (cost=1.18..2.37 rows=28 width=220)"
              Hash Cond: (public.points.oid = public.points.oid)"
              ->  Seq Scan on points  (cost=0.00..1.08 rows=28 width=114)"
              ->  Hash  (cost=1.08..1.08 rows=28 width=110)"
                    ->  Seq Scan on points  (cost=0.00..1.08 rows=28 width=110)"
        ->  Index Scan using "countries_Idx" on countries  (cost=0.00..0.91 rows=1 width=414)"
              Index Cond: (geometry && public.points.geometry)"

太棒了!这似乎也快得多。谢谢!
AdamEstrada 2012年

4

好的。。。我做了一些黑客工作,发现SQL FUNCTION帮了我大忙。有人对将其带到桥上有任何想法吗?

 CREATE OR REPLACE FUNCTION getcountry (
       country_geom geometry
    ) RETURNS TABLE(country text) AS $$
        SELECT b.name as country FROM  
                    geonames d, world_borders b WHERE
                    $1 && b.wkb_geometry 
                    AND intersects($1, b.wkb_geometry) ;
  $$ LANGUAGE SQL;

UPDATE geonames 
    SET country = val
    FROM (SELECT getcountry(point_geom) FROM geonames) AS val
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.