MySQL - 从总线路径数据库获取信息

时间:2010-10-30 11:45:50

标签: sql mysql

我遇到的问题是从以下表中获取数据,其中总线路由包含1次或更多次更改。我还是比较新的SQL。

我有一个包含2个表(bus_route和bus_stop)的数据库。 bus_route包含以下列:

路线 - 公交车的号码
跑 - 公共汽车的方向(1或2)
sequence - 沿路线的停止位置
stop_code - 该停止的唯一代码
stop_name
经度
纬度

bus_stop包含以下列:

stop_code
stop_name
北纬
经度
stop_area - 每个停靠区域有3到8个公共汽车

对于每个总线,bus_route中有20到70行,具体取决于停止次数和bus_stop中每个停止1行。

我已经编写了这个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来查找路线,其中第2条公交车离开第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合并到语句中时遇到问题,找不到第二条公共汽车从同一个stop_area中的另一个站点离开的路径,其中有一个更改。

对上述问题的任何建议或如何使用stop_area将不胜感激。

我还应该提到以下不是我的(我在网上找到了):

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

1 个答案:

答案 0 :(得分:0)

bus_route和bus_stop之间存在1:1的关系。所以从route1到stop1,到同一区域内的所有匹配站点,到具有相同区域的所有匹配路径:

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