I'm refreshing some MySQL skill (hopefully).
I have this query:
SELECT stops.name,
stops.stop_id,
stop_times.trip_id,
stop_times.departure_time,
trips.route_id
FROM stops, routes, stop_times, trips
WHERE stops.stop_id = stop_times.stop_id AND trips.route_id = 2 AND stop_times.trip_id = 'SCHED255'
ORDER BY stops.stop_id ASC
This returns the correct information, but I get multiple occurrences of each record. Any ideas what I'm missing? TIA
You have 4 tables in the FROM
-Clause. So you need at least 3 JOINS
to avoid multiple occurances of data.
Basic Rule: n tables = (n-1) JOINS.
+++++++++++EDIT+++++++++++
In your case it should look like this:
/*WITH EXCPLICIT JOINS*/
SELECT stops.name, stops.stop_id, stop_times.trip_id, stop_times.departure_time, trips.route_id
FROM stops s JOIN routes r ON s.col_name = r.col_name /*col_name is the name of the column that is defined as Contraint between these two*/
JOIN stop_times st ON st.stop_id = s.stop_id
JOIN trips t ON t.route_id = r.route_id
AND t.route_id = 2
AND st.trip_id = 'SCHED255'
ORDER BY s.stop_id ASC
/*THE SAME THING WITH IMPLICIT JOINS*/
SELECT stops.name, stops.stop_id, stop_times.trip_id, stop_times.departure_time, trips.route_id
FROM stops AS s, routes AS r, stop_times AS st, trips AS t
WHERE s.col_name = r.col_name /*JOIN of stops and trips*/
AND st.stop_id = s.stop_id /*JOIN of stop_times and stops*/
AND t.route_id = r.route_id /*JOIN of trips and rutes*/
AND t.route_id = 2 /*Other condition*/
AND st.trip_id = 'SCHED255' /*Other condition*/
ORDER BY s.stop_id ASC
A query with joins might look something like this...
SELECT s.name
, s.stop_id
, st.trip_id
, st.departure_time
, t.route_id
FROM stops s
JOIN routes r
ON r.some_column = something
JOIN stop_times st
ON st.stop_id = s.stop_id
JOIN trips t
ON t.some_column = some_other_table.some_column
WHERE t.route_id = 2
AND st.trip_id = 'SCHED255'
ORDER
BY s.stop_id ASC
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.