MySQL - 如何使用地理位置数据加速搜索?

时间:2014-12-15 21:55:29

标签: mysql sql indexing geolocation haversine

我有一张cars的桌子,我正试图在半径范围内的城市找到所有车辆。这是我正在使用的查询:

SELECT cars.*,
 69.0 * HAVERSINE(cars.latitude,cars.longitude, 32.7802618, -96.80097810000001) AS distance
FROM cars
WHERE cars.latitude BETWEEN 32.7802618 - (100.0 / 69.0)
 AND 32.7802618 + (100.0 / 69.0)
 AND cars.longitude BETWEEN -96.80097810000001 - (100.0 / (69.0 * COS(RADIANS(32.7802618))))
 AND -96.80097810000001 + (100.0 / (69.0 * COS(RADIANS(32.7802618))))
 AND cars.pick_up_available = 0
ORDER BY distances

我正在测试这个查询,但它似乎正在工作(它从一个城市的纬度和经度协调中找到半径100英里范围内的汽车)。但是有一个缺点 - 查询很慢。在表中有300,000条记录,当我运行此查询时,它返回5,400条记录,耗时4.5秒。

我试图通过添加索引加快速度,如下所示: CREATE INDEX idx_latitude_longitude ON cars (latitude, longitude),但没有帮助(需要4.5秒)。

    show index from cars;
        +----------+------------+------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
        | Table  | Non_unique | Key_name               | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
        +----------+------------+------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
        | cars   |          0 | PRIMARY                |            1 | id          | A         |      253096 |     NULL | NULL   |      | BTREE      |         |               |
        | cars   |          1 | idx_latitude_longitude |            1 | latitude    | A         |       84365 |     NULL | NULL   | YES  | BTREE      |         |               |
        | cars   |          1 | idx_latitude_longitude |            2 | longitude   | A         |       84365 |     NULL | NULL   | YES  | BTREE      |         |               |

        3 rows in set (0.13 sec)

提前谢谢你们。

2 个答案:

答案 0 :(得分:0)

SELECT cars.*,
 69.0 * HAVERSINE(cars.latitude,cars.longitude, 32.7802618, -96.80097810000001) AS distance
FROM cars
WHERE cars.pick_up_available = 0
 AND 32.7802618 + (100.0 / 69.0)
 AND cars.longitude BETWEEN -96.80097810000001 - (100.0 / (69.0 * COS(RADIANS(32.7802618))))
 AND -96.80097810000001 + (100.0 / (69.0 * COS(RADIANS(32.7802618))))
 AND cars.latitude BETWEEN 32.7802618 - (100.0 / 69.0)
ORDER BY distances

这不是一个很大的变化,但它对数据的数学运算有限。

答案 1 :(得分:0)

慢查询有很多原因。不使用索引,排序开销,错误的表结构.... 我的猜测你的查询不能使用索引或排序开销太大。但这只是我的猜测。 你能展示'解释选择'和'SET PROFILING = 1;查询;显示档案;'导致?