mysql – 使用WHERE子句在距经度和纬度的距​​离范围内查找POI

我正在使用以下sql代码找出最接近设定坐标的’ALL’poi,但我想找出特定的poi而不是所有的poi.当我尝试使用where子句时,我得到一个错误,它不起作用,这是我目前卡住的地方,因为我只使用一个表用于所有poi的所有坐标.

SET @orig_lat=55.4058;  
SET @orig_lon=13.7907; 
SET @dist=10;
SELECT 
    *, 
    3956 * 2 * ASIN(SQRT(POWER(SIN((@orig_lat -abs(latitude)) * pi()/180 / 2), 2) 
    + COS(@orig_lat * pi()/180 ) * COS(abs(latitude) * pi()/180) 
    * POWER(SIN((@orig_lon - longitude) * pi()/180 / 2), 2) )) as distance 
FROM geo_kulplex.sweden_bobo
HAVING distance < @dist 
ORDER BY distance limit 10;

解决方法:

问题是您无法在select或where子句中引用别名列(在本例中为distance).例如,你不能这样做:

select a, b, a + b as NewCol, NewCol + 1 as AnotherCol from table
where NewCol = 2

这将同时失败:尝试处理NewCol 1时的select语句以及尝试处理NewCol = 2时的where语句.

有两种方法可以解决这个问题:

1)用计算值本身替换参考.例:

select a, b, a + b as NewCol, a + b + 1 as AnotherCol from table
where  a + b = 2

2)使用外部选择语句:

select a, b, NewCol, NewCol + 1 as AnotherCol from (
    select a, b, a + b as NewCol from table
) as S
where NewCol = 2

现在,考虑到您的巨大且不是非常人性化的计算列:)我认为您应该选择最后一个选项以提高可读性:

SET @orig_lat=55.4058;  
SET @orig_lon=13.7907; 
SET @dist=10;

SELECT * FROM (
  SELECT 
    *, 
    3956 * 2 * ASIN(SQRT(POWER(SIN((@orig_lat -abs(latitude)) * pi()/180 / 2), 2) 
    + COS(@orig_lat * pi()/180 ) * COS(abs(latitude) * pi()/180) 
    * POWER(SIN((@orig_lon - longitude) * pi()/180 / 2), 2) )) as distance 
  FROM geo_kulplex.sweden_bobo
) AS S
WHERE distance < @dist
ORDER BY distance limit 10;

编辑:正如下面提到的@Kaii,这将导致全表扫描.根据您将要处理的数据量,您可能希望避免这种情况,并选择第一个选项,该选项应该更快地执行.

上一篇:echarts (geo/map) 渐变效果


下一篇:Nebula 架构剖析系列(二)图数据库的查询引擎设计