MySQL查询在站点之间查找列车

时间:2014-07-15 14:12:01

标签: mysql

我的列车时间表结构,

Table Name- timming_tb
Train_Number  Station  Time
16636          ABC     09:00am  
16636          CDE     10:00am
16636          FGH     11:00am
16637          FGH     12:00pm
16637          CDE     01:00pm
16637          ABC     02:00pm

用户将作为输入提供 输出将是所有列车编号

即输入From-CDE To-FGH ---->输出将是16636

和输入From-FGH To-CDE ---->输出将是16637

我尝试了以下查询

SELECT Train_Number FROM 'timming_tb' WHERE Station="CDE" or Station="FGH"

但它显示所有列车编号CDE和FGH

3 个答案:

答案 0 :(得分:1)

您应该将您的时间列更改为此计算的标准24小时时间; 那不是太复杂了:

SELECT train_number
  FROM timming_tb tt1
 WHERE tt1.station = 'CDE'
   AND EXISTS (
         SELECT 1
           FROM timming_tb tt2
          WHERE tt2.train_number = tt1.train_number
            AND tt2.station = 'FGH'
            AND tt2.time > tt1.time
       )

N.B如果需要更完整的表,这将返回所有可行的列车,但如果需要,您可以应用一些过滤/订购逻辑。

答案 1 :(得分:0)

使用自联接可以执行以下操作: -

SELECT a.Train_Number
FROM train_time a
INNER JOIN train_time b
ON a.Train_Number = b.Train_Number
AND b.Time > a.Time
WHERE a.Station = 'CDE'
AND b.Station = 'FGH'

假设您有时间的实时字段

如果你只想要直接从CDE到FGH而没有中间站的列车你可以在桌子上添加LEFT OUTER JOIN,寻找时间在另外两个之间的车站: -

SELECT a.Train_Number
FROM train_time a
INNER JOIN train_time b
ON a.Train_Number = b.Train_Number
AND b.Time > a.Time
LEFT OUTER JOIN train_time c
ON a.Train_Number = c.Train_Number
AND c.Time > a.Time 
AND c.Time < b.Time
WHERE a.Station = 'CDE'
AND b.Station = 'FGH'
AND c.Station IS NULL

答案 2 :(得分:0)

以下查询执行自联接。

SELECT 
  tt1.train_number
FROM timming_tb tt1
INNER JOIN timming_tb tt2
ON tt1.train_number = tt2.train_number AND concat(right(tt2.time, 2), replace(tt2.time, '12:', '00:')) > concat(right(tt1.time, 2), replace(tt1.time, '12:', '00:'))
WHERE tt1.station = 'CDE'
AND tt2.station = 'FGH';

SQL Fiddle demo

<强>参考