我正在处理已导入MySql的GTFS数据集,我正在使用PHP访问它。 我正在尝试查找给定时间和日期的特定路线的旅行。 我的Sql查询看起来像这样
'SELECT t.route_id AS route_id, t.service_id AS service_id, t.trip_headsign AS trip_headsign,
t.trip_id AS trip_id,
( SELECT departure_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY departure_time ASC limit 1) AS initial_departure_time,
( SELECT arrival_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY arrival_time DESC limit 1) AS final_arrival_time
FROM trips AS t INNER JOIN calendar_dates AS c
WHERE t.service_id = c.service_id
AND c.date ='.$calendar_date.'
AND initial_departure_time <='.$time.'
AND'.$time. '<=final_arrival_time
AND t.route_id ='.$route.'
ORDER BY trip_id ASC';
$route
,$calendar_date
和$time
都被传入。
查询返回的列未找到:
1054“ where子句”中的未知列“ initial_departure_time”。我认为initial_departure_time无法评估。
我也完全迷失了解决方法。任何线索,请先谢谢
答案 0 :(得分:0)
您不能在WHERE子句中使用别名。
将子查询合并到WHERE子句中:
'SELECT t.route_id AS route_id,
t.service_id AS service_id,
t.trip_headsign AS trip_headsign,
t.trip_id AS trip_id,
(SELECT departure_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY departure_time ASC limit 1) AS initial_departure_time,
(SELECT arrival_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY arrival_time DESC limit 1) AS final_arrival_time
FROM trips AS t INNER JOIN calendar_dates AS c
WHERE t.service_id = c.service_id
AND c.date ='.$calendar_date.'
AND (SELECT departure_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY departure_time ASC limit 1) <='.$time.'
AND'.$time. '<= (SELECT arrival_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY arrival_time DESC limit 1)
AND t.route_id ='.$route.'
ORDER BY trip_id ASC';
或者包装查询,然后在其中使用别名:
'SELECT * FROM (
SELECT t.route_id AS route_id,
t.service_id AS service_id,
t.trip_headsign AS trip_headsign,
t.trip_id AS trip_id,
(SELECT departure_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY departure_time ASC limit 1) AS initial_departure_time,
(SELECT arrival_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY arrival_time DESC limit 1) AS final_arrival_time
FROM trips AS t INNER JOIN calendar_dates AS c
WHERE t.service_id = c.service_id
AND c.date ='.$calendar_date.'
AND t.route_id ='.$route.'
ORDER BY trip_id ASC) a
WHERE a.initial_departure_time <='.$time.'
AND'.$time. '<= a.final_arrival_time';
这可能会加快速度(您可能需要交换MIN
和MAX
):
'SELECT t.route_id AS route_id,
t.service_id AS service_id,
t.trip_headsign AS trip_headsign,
t.trip_id AS trip_id,
MIN(s.departure_time) AS initial_departure_time,
MAX(s.arrival_time) AS final_arrival_time
FROM trips AS t
INNER JOIN calendar_dates AS c ON t.service_id = c.service_id
LEFT JOIN stop_times s ON s.trip_id = t.trip_id
WHERE c.date ='.$calendar_date.'
AND t.route_id ='.$route.'
GROUP BY t.route_id, t.service_id, t.trip_headsign, t.trip_id,
HAVING '.$time.' BETWEEN MAX(s.arrival_time) AND MIN(s.departure_time)
ORDER BY trip_id ASC';