简体   繁体   中英

How to find all pair of polygons which only touch each other in a point and only list each pair once

How to find all pair of polygons which only touch each other in a point and only list each pair once in PostgreSQL using PostGIS? like the cycle shown on the picture:

在此处输入图片说明

I have written the following query:

with kms as (
    select
      a.county as cn1,
      b.county as cn2
    from spatial.us_counties as a, spatial.us_counties as b
    where ST_Touches(a.geom, b.geom) = 'true' and a.id != b.id and ST_GeometryType(ST_Intersection(a.geom,b.geom)) = 'ST_Point'
)
/**    below is for remove reversed pairs  **/
SELECT  t1.cn1
        ,t1.cn2
FROM kms AS t1
    LEFT OUTER JOIN kms AS t2
    ON t1.cn1 = t2.cn2
    AND t1.cn2 = t2.cn1
WHERE   t2.cn1 IS NULL
      OR t1.cn1 < t2.cn1

But this query caused serious performance issue and it returned all pairs twice (reversed pair)

This approach is not the solution at all.

So is there anyone can help me with that or give me any hints?

I'm not absolutely sure so I need your feedback for this answer..

Try:

SELECT DISTINCT A.county
  FROM spatial.us_counties AS A, spatial.us_counties AS B
    WHERE ST_Touches(A.geom, B.geom) = 'true'

According to: https://postgis.net/docs/ST_Touches.html ST_Touches should return touching polygons only and not intersecting so this should eliminate the need for the where statement that checks if it's a point intersection. Selecting DISTINCT should help with the duplicates.

Adding an index https://postgis.net/docs/using_postgis_dbmanagement.html#idm2269 to the table will help speed up the geometry queries. Let me know if you've already done all this, I can edit my answer.

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