b101 b101 - 5 months ago 9
SQL Question

Subselect in MySQL

I have the following table, representing buses and the points at which they stop.

bus_table

bus stop_no station_id
1 1 1
1 2 2
1 3 3
2 1 7
2 2 8
2 3 9
3 1 3
3 2 4
3 3 5
3 4 6
3 5 7


I want to get from station 1 to station 9.

What query can I write for that?

Answer

By way of example. Obviously, this solution is not recursive - but you could just keep iterating through bus routes until you got from A to B.

DROP TABLE IF EXISTS bus_routes;


CREATE TABLE bus_routes 
(bus_no INT NOT NULL
,stop_no INT NOT NULL
,station_id INT NOT NULL
,PRIMARY KEY(bus_no,stop_no)
);

INSERT INTO bus_routes VALUES
(1,1,1),
(1,2,2),
(1,3,3),
(2,1,7),
(2,2,8),
(2,3,9),
(3,1,3),
(3,2,4),
(3,3,5),
(3,4,6),
(3,5,7);

SELECT a_from.bus_no
     , a_from.station_id start_from
     , b_from.station_id first_change_at
     , b_from.bus_no to_bus
     , c_from.station_id then_change_at
     , c_from.bus_no to_bus
     , c_to.station_id alighting_at
  FROM bus_routes a_from  
  JOIN bus_routes a_to 
    ON a_to.bus_no = a_from.bus_no 
   AND a_to.stop_no > a_from.stop_no
  JOIN bus_routes b_from
    ON b_from.station_id = a_to.station_id
  JOIN bus_routes b_to
    ON b_to.bus_no = b_from.bus_no
   AND b_to.stop_no > b_from.stop_no
  JOIN bus_routes c_from
    ON c_from.station_id = b_to.station_id
  JOIN bus_routes c_to
    ON c_to.bus_no = c_from.bus_no
   AND c_to.stop_no > c_from.stop_no
 WHERE a_from.station_id = 1
   AND c_to.station_id = 9;

+--------+------------+-----------------+--------+----------------+--------+--------------+
| bus_no | start_from | first_change_at | to_bus | then_change_at | to_bus | alighting_at |
+--------+------------+-----------------+--------+----------------+--------+--------------+
|      1 |          1 |               3 |      3 |              7 |      2 |            9 |
+--------+------------+-----------------+--------+----------------+--------+--------------+
Comments