Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast search of nearest values in SQL

I have got long/lat coordinates with altitude in SQLite database.

Some example data:

latitude   longitude  altitude
------------------------------
48.003333  11.0       652    
48.036667  11.000833  651
48.280833  11.000833  533

Now i want some SQL query which will give me closest altitude to given latitude/longitude coordinates so for example

Given lat/long will be 48.023445/11.000733 so the closest is altitude 651 with lat/long 48.036667/11.000833. Tried to search a lot of forums but nothing usefull. Everywhere are examples on one variable or very slow queries. I need this query really fast and saw some solution based on UNIONS. I need it fast because i will make about 1,5 milions of queries on this table. I am using transactions and indexing.

like image 449
MartinS Avatar asked Feb 19 '23 00:02

MartinS


2 Answers

For your purpose (point close to searched for coordinates) you might as well minimize using the formula for distances on a plane.

(lat-latitude)*(lat-latitude) + (long-longitude)*(long-longitude)
like image 151
kmkaplan Avatar answered Feb 20 '23 14:02

kmkaplan


The formula for distance between two points on a sphere, using longitude and latitude coordinates is far from simple, and is described here. As specified in the page, if the points are reasonably close, you could get away with simple planar trigonometry, and just use the Euclid distance between the points:

like image 45
SWeko Avatar answered Feb 20 '23 12:02

SWeko