我对MYSQL查询和优化并不是特别了解,所以在这方面我需要一些帮助。我正在查看国际城市表,根据表中的经度值和纬度值找到最近的10个城市。
我使用的查询如下所示:
SELECT City as city,
SQRT(POW(69.1 * (Latitude - 51.5073509), 2) +
POW(69.1 * (-0.1277583 - Longitude) * COS(Latitude / 57.3), 2)) AS distance
from `cities`
group by `City`
having distance < 50
order by `distance` asc
limit 10(经度和纬度值显然是在我的代码中动态放置的)
有时这可能需要我的开发环境大约3-4分钟才能完成。
我在这里犯了什么典型的错误吗?或者我应该使用一个更好的查询来检索这些数据?
任何帮助都将不胜感激。
发布于 2016-11-15 19:10:38
SELECT City as city,
SQRT(POW(69.1 * (Latitude - 51.5073509), 2) +
POW(69.1 * (-0.1277583 - Longitude) * COS(Latitude / 57.3), 2)) AS distance
from `cities`
where SQRT(POW(69.1 * (Latitude - 51.5073509), 2) +
POW(69.1 * (-0.1277583 - Longitude) * COS(Latitude / 57.3), 2)) < 50
order by `distance` asc
limit 10City是唯一的,则在单行上执行聚合。MySQL使用排序操作来实现GROUP BY。
如果City不是唯一的,则HAVING子句中的筛选是在一个任意行上进行的,这肯定不是OP的意图。
select x,... from ... group by x having ... some heavy calculations on x ...https://stackoverflow.com/questions/40606705
复制相似问题