The db has 4 tables, below is each table definition with some sample data.
stop times(this represents a particular 'stop' for a bus along a route on a particular trip)
trip_id arrival_time departure_time stop_id stop_sequence
1 06:54:00 06:54:00 9400ZZMAABM1 0001
1 06:56:00 06:56:00 9400ZZMACRU1 0002
1 06:58:00 06:58:00 9400ZZMABOW1 0003
1 07:00:00 07:00:00 9400ZZMAHEA1 0004
1 07:02:00 07:02:00 9400ZZMAPWC1 0005
routes(this represents a route)
route_id route_short_name route_long_name
MET:MET2:I: 42 ALTRINCHAM - MANCHESTER - BURY
MET:MET2:O: 42 BURY - MANCHESTER - ALTRINCHAM
trips(this represents a particular bus trip)
route_id trip_id trip_headsign
MET:MET2:I: 1 "Bury To Manchester"
MET:MET2:I: 2 "Manchester To Bury"
stops(this represents a bus stop)
stop_id stop_code stop_name
0600MA0001 chegptg "Broken Cross, Fallibroome Road (cnr)"
0600MA0050 chegtjm "Macclesfield, opp Tesco"
0600MA0166 chemjat "Knutsford, Sugar Pit Lane (cnr)"
I want to get all the stops for a given route. To do this is seems I must join the data from the routes, trips, stops and stop times but I cant get it right. Here is the query I tried:
SELECT
routes.route_id,
routes.route_short_name,
trips.trip_id,
stops.stop_id,
stops.stop_name
FROM routes
INNER JOIN trips ON routes.route_id=trips.route_id
INNER JOIN stops ON stop_times.stop_id=stops.stop_id
WHERE routes.route_short_name='42';
Your joins use stop_times
, but this is not in the from
clause. You need all four tables:
SELECT r.route_id, r.route_short_name, t.trip_id, s.stop_id, s.stop_name
FROM routes r INNER JOIN
trips t
ON r.route_id = t.route_id INNER JOIN
stop_times st
ON st.trip_id = t.trip_id INNER JOIN
stops s
on st.stop_id = s.stop_id
WHERE r.route_short_name='42';
I believe this will work for you
SELECT
DISTINCT(s.stop_id),
s.stop_name,
r.route_short_name
FROM stops s
INNER JOIN stop_times st ON st.stop_id = s.stop_id
INNER JOIN trips t ON t.trip_id = st.trip_id
INNER JOIN routes r ON r.route_id=t.route_id
WHERE r.route_short_name='42'
GROUP BY s.stop_id;
you were trying to join a table from a different tables id which doesn't work. you first have to join stop_times to trips and then join stops to stop_times so that your id's match up and you have the stops per corresponding trip.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.