我很努力地在rails中转换sql查询。在给定sql查询的情况下转换复杂查询
背景
我有一个名为总线3个表,停止和调度。总线表具有字段ID和名称。停止表具有字段ID和名称。计划表包含字段标识,bus_id,stop_id,到达和bustag。
这是查询我在SQL
select A.bus_id as busid, A.stop_id as source, A.arrival as atime, B.arrival as dtime from
(SELECT * from schedules as S where S.stop_id = #{startStopId}) A
inner join
(SELECT * from schedules as S where S.stop_id = #{endStopId}) B
on A.bustag = B.bustag
where A.arrival < B.arrival
and A.arrival > CURTIME();
在铁轨我已经做到了这一点至今
@possible_buses = Schedule.where(stop_id: [startStopId,endStopId])
现在我想做的事情一样MySQL查询这是我想进一步处理这个可能的公共汽车列表获得startStop中的公交车列表,其尾部标志等于公共汽车的尾部标志。停止处,起始处的到达时间少于终止处的到达时间。
如果有人能帮助我,我将非常感激。我在轨道查询方面不太好,这对我有很大的帮助。
示例表
BusTable StopTable ScheduleTable
id Name id Name id bus_id stop_id arrival bustag
1 ttc(inbound) 1 mall 1 1 1 3:00 1
2 ttc(outbound) 2 home 2 1 2 3:15 1
3 downtown 3 1 3 3:30 1
4 uptown 4 1 4 3:45 1
5 1 1 3:15 2
6 1 2 3:30 2
7 1 3 3:45 2
8 1 4 4:00 2
9 2 4 2:55 3
10 2 3 3:10 3
11 2 2 3:25 3
12 2 1 3:35 3
13 2 4 3:10 4
14 2 3 3:20 4
15 2 2 3:30 4
16 2 1 3:45 4
示例查询和预期产出
例如,如果用户想从商场走在2:30到住宅区然后将下面的ID应该从返回时间表: - > 1,5。由于这两个Ids都会为您提供bus_id,可以让您从商场到上城。
我希望这个更清楚。请随时索取更多信息。谢谢。
也许我们应该从简化查询 – Strawberry
开始,如果你用表格数据样本和展开结果和/或sqlfiddle来说明你的帖子,那么这将非常有帮助 – Alex
我可以这样做,给我一分钟。谢谢 – Unknowntiou