查找给定坐标的特定半径内的所有位置的查询
Query that finds all locations within a certain radius of a given coordinate
我的数据库有一个 organisation
表,其中有两个小数列 lat
和 lon
表示组织的位置。我试图找到坐标 53.6771, -1.62958
800 公里范围内的所有组织(这大致对应于英国的利兹)。
我使用的查询是
select *
from organisation
where (3959 * acos(cos(radians(53.6771)) *
cos(radians(lat)) *
cos(radians(lon) - radians(-1.62958)) + sin(radians(53.6771)) *
sin(radians(lat)))) < 800
然而,这 returns 位于法国里昂,距英国利兹约 970 公里。我意识到上面的公式做了一些简化的假设(例如将地球的形状视为球体),所以我不希望结果绝对准确,但我应该能做得更好?
我找到了一个公式 here 用于计算两点之间的距离(以公里为单位),我已尝试将其转换为 mysql:
WHERE (6371 * 2 *
ATAN2(
SQRT(
SIN(RADIANS((lat-53.6771)/2)) * SIN(RADIANS((lat-53.6771)/2)) + SIN(RADIANS((lon+1.62958)/2)) * SIN(RADIANS((lon+1.62958)/2)) * COS(RADIANS(lat)) * COS(RADIANS(53.6771))
),
SQRT(
1-(SIN(RADIANS((lat-53.6771)/2)) * SIN(RADIANS((lat-53.6771)/2)) + SIN(RADIANS((lon+1.62958)/2)) * SIN(RADIANS((lon+1.62958)/2)) * COS(RADIANS(lat)) * COS(RADIANS(53.6771)))
)
)) < 800
问题是由于使用英里乘数 (3959) 而不是公里 (6371) 引起的。正确的查询如下所示
select *
from organisation
where (6371 * acos(cos(radians(53.6771)) *
cos(radians(lat)) *
cos(radians(lon) - radians(-1.62958)) + sin(radians(53.6771)) *
sin(radians(lat)))) < 800
我的数据库有一个 organisation
表,其中有两个小数列 lat
和 lon
表示组织的位置。我试图找到坐标 53.6771, -1.62958
800 公里范围内的所有组织(这大致对应于英国的利兹)。
我使用的查询是
select *
from organisation
where (3959 * acos(cos(radians(53.6771)) *
cos(radians(lat)) *
cos(radians(lon) - radians(-1.62958)) + sin(radians(53.6771)) *
sin(radians(lat)))) < 800
然而,这 returns 位于法国里昂,距英国利兹约 970 公里。我意识到上面的公式做了一些简化的假设(例如将地球的形状视为球体),所以我不希望结果绝对准确,但我应该能做得更好?
我找到了一个公式 here 用于计算两点之间的距离(以公里为单位),我已尝试将其转换为 mysql:
WHERE (6371 * 2 *
ATAN2(
SQRT(
SIN(RADIANS((lat-53.6771)/2)) * SIN(RADIANS((lat-53.6771)/2)) + SIN(RADIANS((lon+1.62958)/2)) * SIN(RADIANS((lon+1.62958)/2)) * COS(RADIANS(lat)) * COS(RADIANS(53.6771))
),
SQRT(
1-(SIN(RADIANS((lat-53.6771)/2)) * SIN(RADIANS((lat-53.6771)/2)) + SIN(RADIANS((lon+1.62958)/2)) * SIN(RADIANS((lon+1.62958)/2)) * COS(RADIANS(lat)) * COS(RADIANS(53.6771)))
)
)) < 800
问题是由于使用英里乘数 (3959) 而不是公里 (6371) 引起的。正确的查询如下所示
select *
from organisation
where (6371 * acos(cos(radians(53.6771)) *
cos(radians(lat)) *
cos(radians(lon) - radians(-1.62958)) + sin(radians(53.6771)) *
sin(radians(lat)))) < 800