簡體   English   中英

在設定的半徑內從表 A 計算和返回表 B 中最接近的項目的最快方法是什么

[英]What is the fastest way to calculate and return the closest items in Table B from Table A within a set radius

我在表 1 和表 2 中有大量的經緯度坐標。例如,假設兩個表中有 100,000 個坐標。 我需要從表 1 中返回表 2 中最近的一對坐標,只要它們在表 1 中每個唯一項目(最多 100,000 個項目,但隨后被剔除)的設定最小距離(比如 100 米)內到 100 米是我的預期輸出)。

我對 MSSQL 的 Geometry 和 Geography 部分非常熟悉,並且傳統上會使用以下方法處理以下問題:

Select
Table1ID = T1.ID,
Table2ID = T2.ID,
Distance = T1.PointGeog.STDistance(T2.PointGeog),
Keep = 0
into #Distance 
From #Table1 T1
   cross join #Table2 T2
where T1.PointGeog.STDistance(T2.PointGeog) <= 100

這將返回 Table2 中距離 Table1 100 米以內的所有項目

然后,為了僅限於最近的項目,我可以:

Update #Distance
 set Keep = 1
from #Distance D 
   inner join 
   (select shortestDist = min(Distance), Table1ID from #Distance GROUP BY 
    Table1ID) A
    on A.ID = D.Table1ID and A.shortestDist = D.Distance

然后刪除任何保留 <> 1 的內容

這是有效的,但是它絕對需要永遠。 交叉聯接創建了 SQL 需要處理的大量計算,這導致對 MSSQL 2016 的查詢大約需要 9 分鍾。我可以限制表 1 和表 2 與某些標准進行比較的部分的范圍,但實際上不是很多。 我真的不知道如何讓這個過程更快。 最終,我只需要:最近的項目,從 T2 到 T1 的距離。

我嘗試了幾種不同的解決方案,但我想看看 SO 社區是否對如何更好地優化此類內容有任何其他想法。

嘗試交叉申請:

SELECT 
    T1.ID, TT2.ID, T1.PointGeog.STDistance(TT2.PointGeog)
FROM #Table1 as T1
CROSS APPLY (SELECT TOP 1 T2.ID, T2.PointGeog 
  FROM #Table2 as T2
  WHERE T1.PointGeog.STDistance(T2.PointGeog) <= 100
  ORDER BY T1.PointGeog.STDistance(T2.PointGeog) ASC) as TT2

我嘗試了一個新選項,我認為這是我計算得出的最快速度,大約需要3分鍾。

我將表1更改為:

select
ID,
PointGeog,
Buffer = PointGeom.STBuffer(8.997741566866716e-4)
into #Table1

緩沖區為100/111139(將度轉換為米)

接着

if object_id('tempdb.dbo.#Distance') is not null
drop table #Distance 
Select 
T1ID = T1.ID,
T1Geog = T1.PointGeog,
T2ID = T2.ID,
T2Geog = T2.PointGeog,
DistanceMeters = cast(null as float),
DistanceMiles = cast(null as float),
Keep = 0
Into #Distance
From #Table1 T1
    cross join #Table2 T2
Where T1.Buffer.STIntersects(T2.PointGeom) = 1

它不會計算距離,但會首先將數據集剔除到100米以內的任何內容。 然后,我可以傳遞一條update語句來計算實質上更易於管理的數據集上的距離。

在兩個表的 geom 列上創建空間索引,性能應該不會太差。 就像是:


CREATE SPATIAL INDEX spat_t ON  [#Table1]
    (
        [PointGeog]
    )

我在筆記本電腦上用 10 萬個點進行了一些測試,“加入”花了 3 分鍾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM