寻找最近的邻居查询优化

时间:2019-04-11 08:15:46

标签: sql postgresql join postgis

有两个(简化的)表:

属性:

id | geog
___|_______
 1 | <geog>
 2 | <geog>
 3 | <geog>

兴趣点:

id | name         | category  | geog
___|______________|___________|_______
 1 | X Hospital   | health    | <geog>
 2 | Y Hospital   | health    | <geog>
 3 | Y University | education | <geog>
 4 | Z University | education | <geog>
 5 | Z Restaurant | food      | <geog>
 6 | X Restaurant | food      | <geog>

所需结果:

location_id | distance_to_closest_health | distance_to_closest_education | distance_to_closest_food
____________|____________________________|_______________________________|_________________________
          1 |                        300 |                           500 |                    100
          2 |                        450 |                           550 |                    200
          3 |                        150 |                           600 |                    150

以下查询工作正常,但速度非常慢(随着LIMIT的增加,算术级数会变慢):

SELECT 
    properties.id AS "location_id",
    (SELECT ST_Distance(pois.geog, properties.geog) FROM pois WHERE pois.category = 'health' ORDER BY ST_Distance(pois.geog, properties.geog) LIMIT 1) AS "distance_to_closest_health",
    (SELECT ST_Distance(pois.geog, properties.geog) FROM pois WHERE pois.category = 'education' ORDER BY ST_Distance(pois.geog, properties.geog) LIMIT 1) AS "distance_to_closest_education",
    (SELECT ST_Distance(pois.geog, properties.geog) FROM pois WHERE pois.category = 'food' ORDER BY ST_Distance(pois.geog, properties.geog) LIMIT 1) AS "distance_to_closest_food"
FROM properties 
LIMIT 10;

什么是更好(更快)达到预期结果的方法?

0 个答案:

没有答案