我很努力地在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