0

I have two tables: stop_times and trips -- both tables share trip_id. I want to build a query so that I extract information from both tables using trip_id, but then "filter" that information based on something from the first table.

I came up with this to get my information without the "filtering":

SELECT stop_times.trip_id, stop_times.arrival_time, trips.route_id
FROM stop_times, trips
WHERE stop_times.trip_id = trips.trip_id;

This works fine, but then I try to "filter" using stop_id:

SELECT stop_times.trip_id, stop_times.arrival_time, trips.route_id
FROM stop_times, trips
WHERE stop_times.stop_id IN (SELECT stop_id 
                             FROM stop_times 
                             WHERE stop_id = '81');

but it merges information incorrectly.

1 Answer 1

1

Why did you remove WHERE stop_times.trip_id = trips.trip_id from the second query? This might work.

SELECT stop_times.trip_id, stop_times.arrival_time, trips.route_id
FROM stop_times, trips
WHERE stop_times.trip_id = trips.trip_id
  AND stop_times.stop_id = 81;

But you'd be better off using ANSI join syntax.

SELECT stop_times.trip_id, stop_times.arrival_time, trips.route_id
FROM stop_times
INNER JOIN trips ON stop_times.trip_id = trips.trip_id
WHERE stop_times.stop_id = 81;
Sign up to request clarification or add additional context in comments.

1 Comment

... stop_times JOIN trips USING (trip_id) ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.