简体   繁体   中英

Finding the pair of coordinates closest to each other using SQL

Given a list of coordinates, how can I find the closest pair of coordinates using only ONE SQL statement? I have been stuck on this question for a while now and haven't managed to come up with any ideas yet. Since I'm only allowed to use one sql statement I assume variables are not allowed too.

for visualization:

id lat long
1  -12 35 
2  -1  100
3  -9  3

You can use a self join:

select t1.*, t2.*
from t t1 join
     t t2
     on t1.id < t2.id
order by power(t1.lat - t2.lat, 2) + power(t1.long - t2.long, 2)
limit 1

Longitude and latitude are measures associated with the surface of a sphere (our Earth) and the shortest distances are great circles, not straight lines. This is one reason airplanes flying from New York to Rome fly over Newfoundland. Your Euclidean measure would only be shortest if the world looked like this:

地球的等距矩形投影

This is an equi-rectangular projection of the spherical earth onto a flat map. Note the distortion at the poles. The calculation of great circles is WAY more complex and I doubt you could calculate it in a SQL statement. I suspect, although I have not tried to find any cases, that there are points that calculate as further away but are actually closer as you travel on the earth's surface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM