SQL查询查找经过路线的公交车

SQL query to find the bus travelling through route

有一条table名字的路线,包含bus_id,stop_name和位置(就是停靠点的顺序)。

bus travel in one way according to position


Table: 路线

| bus_id | stop_name | position |
|--------|-----------|----------|
| 1      | Stop_1    | 1        |
| 1      | Stop_2    | 2        |
| 1      | Stop_3    | 3        |
| 1      | Stop_4    | 4        |
| 1      | Stop_5    | 5        |
| 1      | Stop_6    | 6        |
| 1      | Stop_7    | 7        |
| 2      | Ramdom_1  | 1        |
| 2      | Ramdom_2  | 2        |
| 2      | Stop_3    | 3        |
| 2      | Stop_4    | 4        |
| 2      | Stop_5    | 5        |
| 2      | Stop_6    | 6        |
| 2      | Ramdom_3  | 7        |

现在需要找到从 stop_3 到 stop_6 的 bus_id 即 bus_id = 12

示例:\

  1. stop_1stop_6 = 1\
  2. stop_6Ramdom_3 = 2\
  3. stop_6stop_1 = no bus found\

需要MYSQL查询才能找到以上数据

database used Server version: 10.4.21-MariaDB (xamp)

您可以尝试过滤您需要的站点名称并计算站点数

select bus_id 
from route  
stop_name 
group by bus_id
having count(distinct stop_name) = 2 
Select a.*, b.* 
From route a
Join route b on a. bus_id=b.bus_id
Where a.position <b.position
And a.name=[stopname] and b.name=. 
[stopname]