One JOIN works slower than two same SELECT

93 views Asked by At

I have this query:

SELECT *
FROM placex AS place
WHERE ST_DWithin(geometry, (SELECT geometry FROM placex WHERE place_id = 412369), 300)
AND name->'name' = (SELECT name->'name' FROM placex WHERE place_id = 412369)

Lead time: 530-650ms

This query use two SELECT, it's ugly and i want rewrite using joins. But this query:

SELECT same.*
FROM placex AS same
JOIN placex AS place ON place.place_id = 412369
WHERE ST_DWithin(same.geometry, place.geometry, 300)
AND same.name->'name' = place.name->'name';

performed in 2.8sec. All indexes stand by default (by Nominatim). How optimize second query? Or use first and don't worry?

PostgreSQL 9.6.4, POSTGIS 2.3.3 r15473

EXPLAIN (ANALYZE, BUFFERS)

1

There are 1 answers

0
Trung Duong On

I could not guess the cause, but I think you could try to rewrite your second query like this

SELECT same.* 
FROM   placex AS same 
       JOIN (SELECT name, 
                    geometry 
             FROM   placex 
             WHERE  place_id = 412369) AS place 
         ON ST_DWithin(same.geometry, place.geometry, 300) 
            AND same.name->'name' = place.name->'name'; 

Or you could rewrite your first query as

SELECT * 
FROM   placex AS place 
WHERE  EXISTS 
       ( 
              SELECT 1 
              FROM   placex AS same 
              WHERE  same.place_id = 412369 
              AND    ST_DWithin(place.geometry, same.geometry, 300) 
              AND    same.name->'name' = place.name->'name');