sql基于坐标计算距离的优化
如题,下面是最初版的sql,取与目标坐标150千米范围内的记录
select top 10 * from T_Temple a with(nolock) where dbo.[fnGetDistance](37.356976,116.8425,lat,lon)<150 order by a.Id asc
因为我们知道,如果要与目标坐标在150公里,所以经纬度应该在目标坐标点的正负2度范围内(粗略这么认为啊),所以加上一个前提条件,如下:
select top 10 * from T_Temple a with(nolock) where lat between 37.356976-2 and 37.356976+2 and lon between 116.8425-2 and 116.8425+2 and dbo.[fnGetDistance](37.356976,116.8425,lat,lon)<150 order by a.Id asc
这样的话,相比于方案1,方案2还是有性能上的提升,特别是T_Temple表记录比较多时,可在lat,lon上可以建立坐标。
附上ms sql 版的fnGetDistance
CREATE FUNCTION [dbo].[fnGetDistance](@LatBegin REAL, @LngBegin REAL, @LatEnd REAL, @LngEnd REAL) RETURNS FLOAT
AS
BEGIN
--距离(千米)
DECLARE @Distance REAL
DECLARE @EARTH_RADIUS REAL
SET @EARTH_RADIUS = 6378.137
DECLARE @RadLatBegin REAL,@RadLatEnd REAL,@RadLatDiff REAL,@RadLngDiff REAL
SET @RadLatBegin = @LatBegin *PI()/180.0
SET @RadLatEnd = @LatEnd *PI()/180.0
SET @RadLatDiff = @RadLatBegin - @RadLatEnd
SET @RadLngDiff = @LngBegin *PI()/180.0 - @LngEnd *PI()/180.0
SET @Distance = 2 *ASIN(SQRT(POWER(SIN(@RadLatDiff/2), 2)+COS(@RadLatBegin)*COS(@RadLatEnd)*POWER(SIN(@RadLngDiff/2), 2)))
SET @Distance = @Distance * @EARTH_RADIUS
SET @Distance = Round(@Distance * 10000,4) / 10000
RETURN @Distance
END