![](/img/trans.png)
[英]In SQL how do you update each row of the table by finding all rows that are equal for a column, then set another column equal to eachother
[英]How do I calculate the distance of each row in an SQL table with all the rows of another table?
我有三個 SQL 表:
我現在只對前兩張桌子感興趣。 如何將氣象站列表過濾到每個感興趣的城市 100 公里范圍內的氣象站?
我有一個 Microsoft SQL 服務器,如果可能的話,我更願意在 SQL 內進行。
基本上,如果你自己嘗試這樣做,你最終會得到一個笛卡爾積:
select c.*, ws.*
from cities c cross apply
(select ws.*
from (select ws.*,
<complicated expression to calculate distance> as distance
from weather_station ws
) ws
where distance < 100
) ws;
為了獲得氣象站列表,必須對所有城市和氣象站進行比較。 距離計算通常相當昂貴,因此您可以通過“預過濾”來減少它。 例如,在大多數有人居住的地方,100 公里在 1 度緯度和 2 度經度范圍內:
select c.*, ws.*
from cities c cross apply
(select ws.*
from (select ws.*,
<complicated expression to calculate distance> as distance
from weather_station ws
where ws.latitutde between c.latitude - 1 and c.latitude + 1 and
ws.longitude between c.longitude - 2 and c.longitude + 2
) ws
where distance < 100
) ws;
盡管這有幫助,但這本質上仍然是一個過濾的笛卡爾積。
那么,你真的應該怎么做? 如果您關心坐標作為空間數據,您應該查看 SQL 服務器的空間擴展(文檔在這里,特別是geography
類型,因為這與您的需求最相關)。
正如 Gordon 提到的,您可以根據需要定義空間地理數據類型。 您可以按照以下步驟來實現目標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.