我有MySQL DB,巴士路线停止如下:
id | route_id | stop_name | stop_id| arrival_time | departure_time | order
1 | 1 | Stop1 | 500002 | 00:00:00 | 14:20:00 | 2
2 | 1 | Stop2 | 502001 | 15:45:00 | 15:50:00 | 3
3 | 1 | Stop3 | 602001 | 16:38:00 | 16:43:00 | 4
4 | 1 | Stop4 | 600001 | 17:23:00 | 00:00:00 | 5
5 | 2 | Stop5 | 500002 | 00:00:00 | 12:40:00 | 2
6 | 2 | Stop6 | 502001 | 14:05:00 | 14:10:00 | 3
7 | 2 | Stop7 | 602001 | 14:58:00 | 15:03:00 | 4
8 | 2 | Stop8 | 600001 | 15:43:00 | 00:00:00 | 5
并希望获得有关start& amp;的信息停止按route_id分组。查询是
SELECT MIN(route_stops.order), MAX(route_stops.order), route_stops.route_id, route_stops.stop_name as departure ,latest.stop_name as arrival
FROM route_stops
JOIN (
SELECT stop_name
FROM route_stops rs
WHERE **route_stops.route_id**=rs.route_id
ORDER BY `order` DESC
LIMIT 1
) latest
group by route_id
但遗憾的是有错误说#1054 - 'where子句'中的未知列'route_stops.route_id'
如何将父字段传递给JOINed子查询?
我最初对查询的期望是:
route_id |from_stop_name|to_stop_name
1 | Stop1 | Stop4
2 | Stop5 | Stop8
更新: 找到的解决方案适合我
SELECT rs.route_id, rs.stop_name,rs.stop_id, j.stop_name,j.stop_id
FROM route_stops rs
INNER JOIN (
select d1.*
from `route_stops` d1
left outer join route_stops d2
on (d1.route_id = d2.route_id and d1.`order` < d2.`order`)
where d2.route_id is null
order by route_id
) j on j.route_id=rs.route_id
group by rs.route_id