Question

I have a table filled with bus stops. Each stop has a line_id, a direction and coordinates (lat and lng).

I want my query to return the closest stop for each line/direction.

SELECT * from stops GROUP BY CONCAT(line_id, direction)

That query groups my stops as expected. It's the other part that's tricker (returning the closest stop), since I'm calculating the distance on the fly using (I replaced some variables here)

SQRT(POW(111.1819*(45.54182-lat),2)+POW(64.7938007101048*(-73.62934-lng),2))

I've tried doing an INNER JOIN but no luck (I've replaced the distance formula):

SELECT distance-formula as distance1, s1.* from stops s1 INNER JOIN 
(SELECT MIN(distance-formula) AS distance2, line_id, direction FROM stops GROUP BY CONCAT(line_id, direction)) s2 
ON (s1.line_id = s2.line_id AND s1.direction = s2.direction AND s1.distance1 = s2.distance2)

But I keep getting a Unknown column 'distance1' in 'on clause' error.

I've looked into other options but the fact that the distance is calculated within the query seems to be a real deal-breaker. What are my options? I need my query to be as fast as possible.

Was it helpful?

Solution

Untested:

SELECT * FROM (SELECT distance-formula as distance1, line_id, direction from stops) s1 INNER JOIN (SELECT MIN(distance-formula) AS distance2, line_id, direction FROM stops GROUP BY CONCAT(line_id, direction)) s2 ON (s1.line_id = s2.line_id AND s1.direction = s2.direction AND s1.distance1 = s2.distance2)

Or (also untested):

SELECT distance-formula as distance1, s1.* from stops s1 INNER JOIN (SELECT MIN(distance-formula) AS distance2, line_id, direction FROM stops GROUP BY CONCAT(line_id, direction)) s2 ON (s1.line_id = s2.line_id AND s1.direction = s2.direction AND s1.distance - formula = s2.distance2)

You can't use the alias distance1 in your where or on clause unless its in a subquery like the first example.

Also, in the interest of speeding up your calculations, you don't need to take the square root of anything because sqrt(x) < sqrt(y) implies x < y

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