首页 > 解决方案 > 需要帮助来优化 mysql 查询

问题描述

我正在使用以下查询使用纬度和经度从城市表中搜索离我所在位置最近的城市。该查询还检查离我最近的城市是否有超过 1 个给定类别的商店。只有这样才能选择一个城市。

查询工作正常,但执行时间超过 5 秒。有什么方法可以优化此查询以减少时间。

SELECT id,city,city_url, 
(SELECT count(shop) FROM shops JOIN         
shop_categories ON shop_categories.shop_id = shops.id WHERE 
city_id=cities.id && shop_categories.category_id = :catId LIMIT 1) as 
totalshops, 
(6371 * 2 * ASIN(SQRT( POWER(SIN(( :latitude - latitude) *  
pi()/180 / 2), 2) +COS( :latitude * pi()/180) * COS( :latitude * 
pi()/180) * POWER(SIN(( :longitude - longitude) * pi()/180 / 2), 2) ))) 
as distance
from cities
having totalshops > 1
order by distance ASC
LIMIT 1

标签: mysql

解决方案


推荐阅读