我一直在試圖爲公共交通系統編寫一個查詢,當我輸入起點和終點站號時,它將輸出路線列表。嵌套的MySQL查詢
這裏是我的MySQL表:
mysql> desc route_timings;
+----------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+---------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| route_number | int(11) | NO | | NULL | |
| stop_number | int(11) | NO | | NULL | |
| arrival_time | time | YES | | NULL | |
| departure_time | time | YES | | NULL | |
+----------------+---------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
下面是樣本值:
mysql> select * from route_timings;
+----+--------------+-------------+--------------+----------------+
| ID | route_number | stop_number | arrival_time | departure_time |
+----+--------------+-------------+--------------+----------------+
| 1 | 54 | 1 | 10:00:00 | 10:05:00 |
| 2 | 54 | 2 | 11:00:00 | 11:05:00 |
| 3 | 54 | 3 | 12:00:00 | 12:05:00 |
| 4 | 55 | 3 | 13:00:00 | 13:05:00 |
| 5 | 55 | 4 | 14:00:00 | 14:05:00 |
| 6 | 55 | 5 | 15:00:00 | 15:05:00 |
| 7 | 60 | 3 | 10:00:00 | 10:05:00 |
| 8 | 60 | 2 | 11:00:00 | 11:05:00 |
| 9 | 60 | 1 | 12:00:00 | 12:05:00 |
+----+--------------+-------------+--------------+----------------+
9 rows in set (0.01 sec)
我的問題是:如果我想列出ROUTE_NUMBER的,將包含stop_number 1和stop_number 3,我會寫類似這樣的查詢:
SELECT DISTINCT `route_number` FROM `route_timings` WHERE `route_number` IN (
SELECT `route_number` FROM `route_timings` WHERE `stop_number`=1
) AND `route_number` IN (
SELECT `route_number` FROM `route_timings` WHERE `stop_number`=3
);
但是,上面的查詢只會返回包含兩個站點的route_number,而不是源站點(1)在目標站點(3)之前到達的路線。
查詢將返回以下:
+--------------+
| route_number |
+--------------+
| 54 |
| 60 |
+--------------+
的ROUTE_NUMBER 60不會從1開始,到3,而是從3開始並且前往1.是否有人可以幫助我,有點添加到查詢以便查詢僅輸出其中stop_number 1的到達時間小於stop_number 3的到達時間的route_number。
在此先感謝。 -Shain
這就是我一直在尋找。非常感謝你。 – 2012-03-13 09:28:14