我正在刷新一些MySQL技能(希望如此)。
我有这个问题:
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
这会返回正确的信息,但我会多次出现每条记录。我缺少什么想法? TIA
答案 0 :(得分:2)
FROM
- 条款中有4个表格。因此,您至少需要3 JOINS
才能避免多次出现数据。
基本规则:n tables =(n-1)JOINS。
+++++++++++ EDIT +++++++++++
在你的情况下它应该是这样的:
/*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
答案 1 :(得分:1)
带有连接的查询可能看起来像这样...
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