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

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

路线-公交车号
运行-公交车方向(1或2)
顺序-沿路线停靠点的位置
stop_code-该停靠点的唯一代码
stop_name
经度
纬度

bus_stop包含以下列:

停止码
stop_name
纬度
经度
stop_area-每个停止区域3到8辆巴士

对于每个公交车,bus_route中有20到70行,具体取决于站点的数量,而bus_stop中每个站点有1行。

我已编写此SQL来获取行,其中在2个位置之间有直接路由:

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:

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中的另一站离开的路线更改为1的路线。

任何有关上述查询或我如何使用stop_area的建议,将不胜感激。

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

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

最佳答案

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

09-18 02:02