I have a table with a list of users, which looks something like;
Users.. ( id, username, lat, long )
I have a location table which looks like this:
Locations.. ( id, name, lat, lng, bound_ne_lat, bound_ne_lng, bound_sw_lat, bound_sw_lng
What I'm trying to do, is something like;
SELECT Users.*, Locations.name as NearestTown
FROM Users
INNER JOIN Locations ON ( .. lookup nearest town from Locations based on Users lat lng coords, return only the nearest result .. )
I did think about doing some kind of subquery, like;
INNER JOIN Locatios ON Locations.id IN (SELECT id FROM Locations ORDER BY (..distance query) desc limit 1
But then I found out I couldn't pass the users lat / lng into to the sub query for each result.
The current formula I do use however to calculate the distance between the 2 points is;
(3956 * 2 * ASIN(SQRT( POWER(SIN((@sourceLat - table.lookupLat) * pi()/180 / 2), 2) +COS(@sourceLat * pi()/180) * COS(table.lookupLat * pi()/180) * POWER(SIN((@sourceLng - table.lookupLng) * pi()/180 / 2), 2) ))) as Distance,
However, how could I use this in a subquery [if the best option] when I cannot pass in the @sourceLat and @sourceLng for each result .. ?
Any help, most appreciated.