MYSQL: How to use outer aliases in subquery properly?
The first query works just fine. It returns one row from the table 'routepoint'. It has a certain 'route_id' and 'geo_distance()' is on its minimum given the parameters. I know that the 开发者_如何学Csubquery in the FROM section seems unnecessarily complicated but in my eyes it helps to highlight the problem with the second query.
The differences are in the last two rows.
SELECT rp.*
FROM routepoint rp, route r, (SELECT * FROM ride_offer WHERE id = 6) as ro
WHERE rp.route_id = r.id
AND r.id = ro.current_route_id
AND geo_distance(rp.lat,rp.lng,52372070,9735690) =
(SELECT MIN(geo_distance(lat,lng,52372070,9735690))
FROM routepoint rp1, ride_offer ro1
WHERE rp1.route_id = ro1.current_route_id AND ro1.id = 6);
The next query does not work at all. It completely freezes mysql and I have to restart. What am I doing wrong? The first subquery returns excactly one row. I don't understand the difference.
SELECT rp.*
FROM routepoint rp, route r, (SELECT * FROM ride_offer WHERE id = 6) as ro
WHERE
rp.route_id = r.id
AND r.id = ro.current_route_id
AND geo_distance(rp.lat,rp.lng,52372070,9735690) =
(SELECT MIN(geo_distance(lat,lng,52372070,9735690))
FROM routepoint rp1
WHERE rp1.route_id = ro.current_route_id);
The problem is, as pointed out by Romain, that this is costly.
This article describes an algorithm that reduces the cost by a 2-step process.
Step 1: Find a bounding box that contains at least one point.
Step 2: Find the closest point by examining all points in the bounding box, which should be a comparatively small number, thus not so costly.
精彩评论