如何在 mysql 数据库中存储公交路线的方向?

How can I store the direction of a bus route in mysql database?

我有3条table:路线,Bus_stop,路线-Bus_stop
路线:id,工作日,周末
Bus_stop: id, 名字
Route-Bus_stop: 主键(order, time), 外键: idRoute, idBus_stop

Insert into Route(id,weekday,weekend) values(1,1,1);
Insert into Route(id,weekday,weekend) values(2,1,1);

Insert into Bus_stop(id,name) values(1,'A');
Insert into Bus_stop(id,name) values(2,'B');
Insert into Bus_stop(id,name) values(3,'C');

Insert into Route-Bus_stop(idRoute,idBus_stop,routeo_rder,stoptime) values(1,1,0,7:00);
Insert into Route-Bus_stop(idRoute,idBus_stop,route_order,stoptime) values(1,2,1,7:10);
Insert into Route-Bus_stop(idRoute,idBus_stop,route_order,stoptime) values(1,3,2,7:30);

Insert into Route-Bus_stop(idRoute,idBus_stop,route_order,stoptime) values(2,3,0,15:00);
Insert into Route-Bus_stop(idRoute,idBus_stop,route_order,stoptime) values(2,2,1,15:10);
Insert into Route-Bus_stop(idRoute,idBus_stop,route_order,stoptime) values(2,1,2,15:20); 
-- this is only an example, my database is bigger.

其中一条路线为 A -> B -> C,另一条路线为 C->B->A
如果用户想去 A 到 C,我怎样才能只显示一条路线以及所有到目的地的公交车站?
我写了这个查询,但这显示了两条路线。

select *idRoute from Route-Bus_stop where idBus_stop=1 or idBus_stop=3 order by time; // A -> C

这将显示路线 A->C 和 C->A。但我只想要 A->C

首先不要使用 ORDER 或 TIME 等保留字作为列名,这样您就可以避免在所有时间使用反引号

另外 Route-Bus_stop 没有反引号也是无效的。

对于您的查询,您使用自连接来获取起点和终点

CREATE TABLE Route_Bus_stop (
idRoute int
,idBus_stop int 
,`order` int 
,`time` varchar(10))
Insert into Route_Bus_stop(idRoute,idBus_stop,`order`,`time`) values(1,1,0,'7:00');
Insert into Route_Bus_stop(idRoute,idBus_stop,`order`,`time`) values(1,2,1,'7:10');
Insert into Route_Bus_stop(idRoute,idBus_stop,`order`,`time`) values(1,3,2,'7:30');

Insert into Route_Bus_stop(idRoute,idBus_stop,`order`,`time`) values(2,3,0,'15:00');
Insert into Route_Bus_stop(idRoute,idBus_stop,`order`,`time`) values(2,2,1,'15:10');
Insert into Route_Bus_stop(idRoute,idBus_stop,`order`,`time`) values(2,1,2,'15:20'); 
SELECT r1.idRoute,r1.idBus_stop,r2.idBus_stop,r1.`time`, r2.`time`
FROM Route_Bus_stop r1 INNER JOIN Route_Bus_stop r2
ON r1.idRoute = r2.idRoute AND r1.`order` < r2.`order`
WHERE r1.idBus_stop = 1 
AND r2.idBus_stop = 3
idRoute | idBus_stop | idBus_stop | time | time
------: | ---------: | ---------: | :--- | :---
      1 |          1 |          3 | 7:00 | 7:30

db<>fiddle here