I try to run this really simple spatial query with PostgreSQL+Postgis extension.
CASE 1:
SELECT a.id, b.id
FROM PolygonLayer1 a, PolygonLayer2 b
WHERE St_intersects(a.geom,st_centroid(b.geom))
CASE 2:
SELECT a.id, b.id
FROM PolygonLayer1 a, PolygonLayer2 b
WHERE St_intersects(st_centroid(a.geom),b.geom) -- This time I get the centroid of PolygonLayer1
Both PolygonLayer1 (~8000 features) and PolygonLayer2 (~10000 features) are polygons (or Multipolygons).
- The case 1 run in less than 10 seconds
- The case 2 never ends
I really don't understand the difference between the 2 cases.
So the question: What is the difference between the 2 cases ? How can I get a working query for both cases ?
Specification:
- If I run:
EXPLAIN CASE1
, I get a cost of ~20'000 "operations"
"Nested Loop (cost=0.00..21878.84 rows=196 width=8)" " Join Filter: _st_intersects(st_centroid(a.geom), b.geom)" " -> Seq Scan on superposition_bruit a (cost=0.00..6089.04 rows=8804 width=728)" " -> Index Scan using affectation_com_old_geom_gist on affectation_com_old b (cost=0.00..1.53 rows=1 width=591)" " Index Cond: (st_centroid(a.geom) && geom)"
========================================================================
- If I run:
EXPLAIN CASE2
, I get a cost of ~40'000'000 "operations"
"Nested Loop (cost=0.00..40530509.25 rows=196 width=8)" " Join Filter: ((a.geom && st_centroid(b.geom)) AND _st_intersects(a.geom, st_centroid(b.geom)))" " -> Seq Scan on superposition_bruit a (cost=0.00..6089.04 rows=8804 width=728)" " -> Materialize (cost=0.00..3813.98 rows=13332 width=591)" " -> Seq Scan on affectation_com_old b (cost=0.00..2744.32 rows=13332 width=591)"
WHERE St_intersects(st_centroid(a.geom),b.geom) AND St_intersects(a.geom,b.geom)
and it will work.