Question

So, I have a database in which "routes" are saved (i.e. start points and end points, in the Latitude/Longitude format 'StartLat', 'StartLng' and 'EndLat', my'EndLng'). Currently, people can search for these routes by either their start point or their end point (e.g. "Find and routes where the start point is within 5 miles of my LatLng position."). They can look them up by either their start point or their end point (e.g. "find start points within range of this marker", or "find end points within range of this marker").

I currently have a SQL lookup based on the Haversine formula, and this works very well for me.

What I want to be able to do is join two queries together in a single SQL string to be able to "find all routes where the start point is within 'x' miles of "Place A" and the end point is within 'x' miles of "Place B".

I have a feeling that the most elegant way of doing this is to create a join on my existing SQL string, but I can't for the life of me work out how!

My current SQL string looks like this:

SELECT ID, RouteCode, (3959 * acos(cos(radians('51.5073346')) * cos(radians( EndLat )) * cos(radians( EndLng ) - radians('-0.1276831')) + sin(radians('51.5073346')) * sin(radians( EndLat )))) AS distance FROM markers HAVING distance < 15

(So, in this example above, users would be searching for all routes where the End Point is within 15 miles of the co-ordinates 51.5073346, -0.1276831. If they had wanted to find routes where the Start Point was within 15 miles of their LatLng, then EndLat and EndLng would be replaced by StartLat and StartLng).

Does anyone have a great enough understanding of SQL commands to be able to help me work out the SQL string that I need?

Was it helpful?

Solution

You don't need a join; you simply need to add a second condition to your query:

SELECT ID, 
       RouteCode, 
       (
           3959 * acos(cos(radians('51.5073346')) * cos(radians( EndLat )) * 
           cos(radians( EndLng ) - radians('-0.1276831')) + 
           sin(radians('51.5073346')) *      
           sin(radians( EndLat )))
       ) AS end_distance,
       (
           [similar calculation for start here]
       ) AS start_distance
    FROM markers 
    HAVING start_distance < 15 and end_distance < 15

Conceptually, a join is for adding data from another table. You simply want to impose another requirement within the same table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top