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