简体   繁体   中英

A mysql query about the times of train transferring

A table has the id of train and the id of station of the train.

train_id,   station_id
 1            1
 1            2
 1            3
 2            3
 2            4
 3            4
 3            5

I want to check whether I can from station 1 to station 5 by transferring train 2 times. Ans: 1-2-3 transfer at station 3, station 4. I want to check whether I can from station 1 to station 4 by transferring train 1 times. Ans: 1-2 transfer at station 3.

My idea is to join the table by the times of transferring, but I don't know how to join only when the train has common station.

Disclaimer: I realize it's inefficient, but I warned that you wouldn't do that in SQL

Just for fun created a sketch that works for one transfer:

    SELECT DISTINCT l.train_id s1,
                    r.train_id s2
      FROM routes l
INNER JOIN routes r
     WHERE (l.train_id, r.train_id) IN (SELECT l.train_id tl,
                                               r.train_id tr
                                          FROM routes l
                                    INNER JOIN routes r ON l.station_id = r.station_id
                                         WHERE l.train_id IN (SELECT train_id
                                                                FROM routes
                                                               WHERE station_id = 1))
                                                                       --         ^
                                                                       -- start point

       AND r.station_id = 4 -- <-- end point

This query outputs the possible routes in terms of train numbers, you can find the transfer stations from it easily.

Some explanation:

  1. The most nested query selects all the trains that stop on the initial station
  2. Next query finds all the trains that share any stations with every train from #1
  3. The outer query matches the combinations that have the start and the end point in their route

PS: it would be possible to make it a bit more readable if mysql supported CTE s ( WITH ), but it does not :-)

sqlfiddle: http://sqlfiddle.com/#!2/796183/14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM