LIMIT with ORDER BY slowdown query solution for geospacial mysql 5.7

时间:2016-04-25 09:23:30

标签: mysql performance sql-order-by geospatial mysql-5.7

On a geospacial search with a geospacial index on geom field , my time query increase anormaly when i want to ORDER BY distance , is there an alternative syntax ou tricks to avoid that ? Note i'm aware about this post: https://explainextended.com/2011/02/11/late-row-lookups-innodb/ but this trick cannot be achieve with the query bellow :

this query without order by take 0.005s

SELECT 
ST_Distance_Sphere(Point(2.34, 48.85), geom)  as distance
FROM testgeo1
WHERE ST_Contains( ST_MakeEnvelope(
                    Point((2.34+(500/111)), (48.85+(500/111))),
                    Point((2.34-(500/111)), (48.85-(500/111)))
                 ), geom ) 
   LIMIT 500

EXPLAIN :

+----+-------------+----------+------------+-------+---------------+----------+---------+------+------+----------+-------------+
| id | select_type | table    | partitions | type  | possible_keys | key      | key_len | ref  | rows | filtered | Extra       |
+----+-------------+----------+------------+-------+---------------+----------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | testgeo1 | NULL       | range | sp_index      | sp_index | 34      | NULL | 2609 |   100.00 | Using where |
+----+-------------+----------+------------+-------+---------------+----------+---------+------+------+----------+-------------+

this one with ORDER BY takes 0.16s

    SELECT 
    ST_Distance_Sphere(Point(2.34, 48.85), geom)  as distance
    FROM testgeo1
    WHERE ST_Contains( ST_MakeEnvelope(
                        Point((2.34+(500/111)), (48.85+(500/111))),
                        Point((2.34-(500/111)), (48.85-(500/111)))
                     ), geom ) 
ORDER BY distance
       LIMIT 500

solutions , suggestion , alternative syntax or tricks are welcome ..

1 个答案:

答案 0 :(得分:0)

如果信封内有数千个点,......

  • 第一个查询(无ORDER BY)将选择它在该信封中找到的前500个。
  • 第二个查询(带ORDER BY)必须找到信封中的所有点,计算每个点的距离,对结果进行排序,然后提供500个。

这是关于LIMIT有和没有ORDER BY的简单事实。它与SPATIAL或5.7没有任何关系。

请提供证据证明我在做什么

SELECT COUNT(*) 
    FROM testgeo1
    WHERE ST_Contains( ST_MakeEnvelope(
                Point((2.34+(500/111)), (48.85+(500/111))),
                Point((2.34-(500/111)), (48.85-(500/111)))
             ), geom ) ;
相关问题