10


I have the following table:

+--------+----------+---------+---------+---------
|  From  |    To    |Departure| Arrival |   ID   | 
+--------+----------+---------+---------+---------
|   A    |    B     |   0900  |   0930  |   1    | 
+--------+----------+---------+---------+---------
|   C    |    D     |   1000  |   1030  |   2    | 
+--------+----------+---------+---------+---------
|   B    |    C     |   1100  |   1130  |   3    | 
+--------+----------+---------+---------+---------
|   D    |    E     |   1200  |   1230  |   4    | 
+--------+----------+---------+---------+---------
|   C    |    D     |   1300  |   1330  |   5    | 
+--------+----------+---------+---------+---------


  • Departure/Arrival time and ID are always ascending;
  • C_D can be found before and after B_C.

I wish to go from A to D, so the travel route should be ID1, ID3, ID5 or A_B, B_C, C_D.

Any help is appreciated.
Thanks.

azost
  • 571
  • 11
  • 22
  • 1
    I think its not possible to do with one query, you should write function. – Kasyx Apr 04 '14 at 11:55
  • what you want in this table, like what,... I cant understand your question, `go from A to D, so the travel route should be ID1, ID3, ID5 or A_B, B_C, C_D.` – jmail Apr 04 '14 at 12:06
  • Just a note how would you deal with delayed arrival times ? – Oliver Bayes-Shelton Apr 04 '14 at 12:11
  • My interpretation is that he needs to find a route from X yo Y given a train/bus/plane/whatever schedule. I'm pretty sure its not possible to do this without a function/procedure (which would also be fairly complicated). – Vatev Apr 04 '14 at 12:13
  • You have only ABCDE or anything else is also possible? – user2009750 Apr 04 '14 at 12:17
  • I think in other words he is asking to get the rout to A to D. – Pramod Apr 04 '14 at 12:19
  • @user1320951, do you want to calculate time or what – jmail Apr 04 '14 at 12:31
  • Yes Pramod, i wish to get a route from A to D, but since there are no direct routes between A and D, i need to build a route (A_B, B_C, C_D). There is no problem with delayed arrival times. Jmail, i want to build only a route, the times only serve to see if it helps accomplishing what i want.I have more than ABCDE. Ok, i will go for a function (PHP), but how can i achieve it? – azost Apr 04 '14 at 12:32
  • 3
    He just wants to get the route, knowing the starting and ending point. As in getting a list of IDs of middle points. I think the question is fairly well written. The answer however is not simple, doing it in one query would be very difficult (if possible). You should probably write a function. Since you not only have to deal with the actual route but with the departure and arrival times... – aurbano Apr 04 '14 at 12:33
  • This sound more like a job from code than a database query. Maybe you can do it on a store procedure but you need to use cursors... – ericpap Apr 04 '14 at 12:44
  • [this question](http://stackoverflow.com/questions/7245840/pathfinding-routing-trip-planning-algorithms-on-graphs-with-time-restric) might be helpful. – Vatev Apr 04 '14 at 13:20
  • Also, [this link](http://www.artfulsoftware.com/infotree/qrytip.php?id=766). – Aioros Apr 04 '14 at 13:50

3 Answers3

1

You could solve this in a stored procedure. But this algorithm will probably be faster when executed in memory by a programming language. Just make sure that you have the complete data set loaded, so you won't have to execute a query every iteration.

pseudo code:

to = 'D'
prev_to = 'A'
array = array();
while (prev_to != 'D') {
  select arrival, to into prev_arrival, prev_to
  from table 
  where departure > prev_arrival 
  and from = prev_to;

  array[] = [arrival => prev_arrival, to => prev_to]
}

return array

Edit: I guess I had nothing better to do ;)

This class will search all routes from A to D between given start and end time. Just like a public transport app. You might want to use your own database connection methods. (Just don't use mysql_* functions anymore)

<?php

class RoutePlanner
{
    /** @var string */
    protected $departureTime;
    /** @var string */
    protected $departureLocation;
    /** @var string */
    protected $arrivalTime;
    /** @var string */
    protected $arrivalLocation;
    /** @var array */
    protected $schedule;
    /** @var mysqli */
    protected $db;

    /**
     * @param string $departureTime
     * @param string $departureLocation
     * @param string $arrivalTime
     * @param string $arrivalLocation
     * @throws InvalidArgumentException
     */
    public function __construct($departureTime, $departureLocation, $arrivalTime, $arrivalLocation)
    {
        $this->departureTime = $departureTime;
        $this->departureLocation = $departureLocation;
        $this->arrivalTime = $arrivalTime;
        $this->arrivalLocation = $arrivalLocation;
    }

    /**
     * @return array
     */
    public function getRoutes()
    {
        $schedule = $this->fetchSchedule();
        $routes = $this->searchRoutes($schedule);
        return $routes;
    }

    /**
     * Search all routes that start and end between given times
     * @param array $schedule - passing as parameter to ensure the order of execution
     * @return array
     */
    protected function searchRoutes(array $schedule)
    {
        $routes = array();

        foreach ($schedule as $i => $row)
        {
            if ($row['from'] == $this->departureLocation)
            {
                $routes[] = $this->getRoute($schedule, $i);
            }
        }

        return $routes;
    }

    /**
     * Get the route when starting at given point and time
     * @param $schedule
     * @param $start
     * @return array
     */
    protected function getRoute($schedule, $start)
    {
        $steps = array();

        $from = $this->departureLocation;
        $time = $this->departureTime;

        for ($i = $start; $i < count($schedule); $i++)
        {
            $row = $schedule[$i];
            if ($row['from'] == $from && $row['departure'] > $time)
            {
                $steps[] = $row;
                $from = $row['to'];
                $time = $row['arrival'];
            }
        }

        return $steps;
    }

    /**
     * @return array
     */
    protected function fetchSchedule()
    {
        if (! empty($this->schedule))
            return $this->schedule;

        $sql = "select * from schedule where departure >= ? and arrival <= ?";

        $db = $this->getDatabase();
        $statement = $db->prepare($sql);
        $statement->bind_param("ss", $this->departureTime, $this->arrivalTime);
        $statement->execute();
        $result = $statement->get_result();

        $this->schedule = $result->fetch_all(MYSQLI_ASSOC);

        $statement->close();
        $result->free();

        return $this->schedule;
    }

    /**
     * @return mysqli
     */
    protected function getDatabase()
    {
        if (empty($this->db))
            $this->db = new mysqli('localhost', 'user', 'pass', 'database');

        return $this->db;
    }

    public function __destroy()
    {
        if (! empty($this->db))
            $this->db->close();
    }
}

Use like:

<?php

$planner = new RoutePlanner('Amsterdam', '0300', 'Berlin', '1030');
$routes = $planner->getRoutes();
winkbrace
  • 2,682
  • 26
  • 19
1

You can cross join the table on itself to get each step and then you can run a loop in your PHP or whatever that checks the departure and arrival times to make sure the departure is after the arrival of the previous trip:

So, you will need some kind of conditional logic, but this is the basic idea behind the SQL:

SELECT a.id,b.id,a.From, a.To, a.Departure,a.Arrival,
b.From,b.To,b.Departure,b.Arrival
FROM travel a
JOIN travel b
ON a.To = b.From
WHERE a.From = 'A'
OR b.To = 'D'
ORDER BY a.Arrival,a.Departure ASC,
b.Arrival,b.Departure ASC;

If you want to do the whole thing in one swoop you could join the table on itself a third time and then use WHERE a.From = 'A' AND c.To = 'D', however I think it would be more efficient to just do a single join on itself and then use conditional logic in a loop and the WHERE clause to calculate the trip.

SQLFiddle

Alex W
  • 37,233
  • 13
  • 109
  • 109
0

this not possible using MySQL query. However, you can achieve this using your programming language such as php, asp (web), c# (windows), etc.

Jassim Rahma
  • 93
  • 1
  • 3
  • 13