所有路线均从一站出发

时间:2014-07-07 21:22:10

标签: mysql sql

我有这个查询,我的目标是显示从特定停靠点出发的路线:

SELECT stops.stop_id, 
stops.stop_name, 
stops.stop_lat, 
stops.stop_lon, 
stops.zone_id, 
GROUP_CONCAT( distinct rt.route_short_name) as routes
FROM routes rt, trips tr, stop_times st, stops
WHERE rt.route_id = tr.route_id
and tr.trip_id = st.trip_id
and st.stop_id = stops.stop_id
and st.stop_id = 514

我想为我的搜索查询实现相同的目标,现在很简单:

SELECT stop_id, stop_name, stop_lat, stop_lon, zone_id FROM stops WHERE stop_name LIKE '%$search_term%'

如何在我的搜索结果中显示与每个停靠点相关联的路线的停止名称?

1 个答案:

答案 0 :(得分:1)

st.stop_id = 512替换为stop.stop_name LIKE '%search%',将两个where子句合并。

您还需要GROUP BY子句,因为您的原始查询是隐式分组的。

SELECT
    stops.stop_id, 
    stops.stop_name, 
    stops.stop_lat, 
    stops.stop_lon, 
    stops.zone_id, 
GROUP_CONCAT( distinct rt.route_short_name) as routes
FROM routes rt, trips tr, stop_times st, stops
WHERE rt.route_id = tr.route_id
and tr.trip_id = st.trip_id
and st.stop_id = stops.stop_id
and stops.stop_name LIKE '%$search_term%'
GROUP BY
    stops.stop_id, 
    stops.stop_name, 
    stops.stop_lat, 
    stops.stop_lon, 
    stops.zone_id