2010-10-30 230 views
1

我遇到的問題是從以下表格中獲取數據,其中公交路線包含1個更改或更多。我對SQL還比較陌生。MySQL - 從公交路線數據庫獲取信息

我有一個數據庫包含2個表(bus_route和bus_stop)。 bus_route包含以下列:

路線 - 總線
運行的數量 - 在總線的方向(或1 2)
序列 - 沿着該路線的停止
stop_code的位置 - 獨特代碼即停止
stop_name
經度
緯度

bus_stop包含以下幾列:

stop_code
stop_name
緯度
經度
stop_area - 3至8個公共汽車每停止區域

對於每個總線有20之間和70根據停車次數和在每停止1行中bus_route行公交車站。

我寫了這個SQL讀取行,我們有兩個地點之間的直接路線:

SELECT distinct route 
from bus_route 
where 
SQRT(POW((69.1 * (latitude - {startLocationLatitude})) , 2) + 
POW((53 * (longitude - {startLocationLongitude})), 2)) < 0.3 
and route in (SELECT distinct route 
from bus_route 
where 
SQRT(POW((69.1 * (latitude - {endLocationLatitude})) , 2) + 
POW((53 * (longitude - {endLocationLongitude})), 2)) < 0.3) 

它運作良好,在返回行,其中的bus_stop是中開始/結束地點0.3英里。

我也寫了下面的SQL與1度的變化,其中第二總線從同一車站離開的,你離開1號巴士尋找路線:

select t1.route, t1.run, t1.sequence, t1.stop_code, t2.route, t2.run, t2.sequence 
from bus_route t1 
inner join bus_route t2 on (t2.stop_code=t1.stop_code) 
where t1.route in (SELECT distinct route 
from bus_route 
where 
SQRT(POW((69.1 * (latitude - {startLocationLatitude})) , 2) + 
POW((53 * (longitude - {startLocationLongitude})), 2)) < 0.3) 
and t2.route in (SELECT distinct route 
from bus_route 
where 
SQRT(POW((69.1 * (latitude - {endLocationLatitude})) , 2) + 
POW((53 * (longitude - {endLocationLongitude})), 2)) < 0.3)) 

兩個語句的工作很好,但我有麻煩將stop_area合併到語句中,以查找1次更改的路線,其中第二班車從另一站停靠在同一個stop_area中。

任何意見上述查詢或我可以如何使用stop_area將不勝感激。

我還要提到的是下面的不是我(我在網上找到的):

SQRT(POW((69.1 * (latitude - {endLocationLatitude})) , 2) + 
POW((53 * (longitude - {endLocationLongitude})), 2)) < 0.3)) 

回答

0

有一個1:bus_route和bus_stop之間的關係1。所以從ROUTE1走,停止1,所有匹配在同一地區停止時,與同一區域內的所有匹配的路由:

route1 -> stop1 => stop2 -> route2 

的一種方式做到這一點會有所改變:

from bus_route t1 
inner join bus_route t2 on t2.stop_code = t1.stop_code 

收件人:

from bus_route t1 
inner join bus_stop s1 on s1.stop_code = t1.stop_code 
inner join bus_stop s2 on s2.stop_area = s1.stop_area 
inner join bus_route t2 on t2.stop_code = s2.stop_code 
+0

非常感謝。這很好。作爲擴展,在執行以下操作時是否存在問題:來自bus_route的 – 2010-11-01 21:12:23

+0

t1 #inner在子字符串上加入bus_stop s2(s2.stop_area,0,3)= substring(s1。stop_area,0,3) 內部連接bus_stop s2在s2.stop_area = s1.stop_area 內部連接bus_route t2在t2.stop_code = s2.stop_code – 2010-11-01 21:12:55

+0

@Ed騎士:好吧,第一個字符的位置是一。所以你可能在尋找'substring(s2.stop_area,1,3)'。否則看起來不錯。 – Andomar 2010-11-01 23:34:46