Please try the SQL given below. This SQL is NOT tested, but should return records with origin_service == destination_service. Please refer to Subqueries with ANY, IN, and SOME
SELECT
a.stop_reference,
b.service_id,
distance(PointFromText('POINT($origin)', 27700),east_north),
c.route_number
FROM
bus_stops a,
service b,
routes c
WHERE
distance(PointFromText('POINT($origin)', 27700),east_north) < 200
AND
a.stop_reference = b.stop_reference
AND
b.service_id = c.service_id
AND
b.service_id IN (
SELECT
DISTINCT e.service_id
FROM
bus_stops d,
service e,
routes f
WHERE
distance(PointFromText('POINT($dest)', 27700),east_north)
+< 200
AND
d.stop_reference = e.stop_reference
AND
e.service_id = f.service_id
ORDER BY
e.service_id,
distance(PointFromText('POINT($dest)', 27700),east_north)
)
ORDER BY
b.service_id,
distance(PointFromText('POINT($origin)', 27700),east_north)
--VC |