SQL加入关系较弱的日期

时间:2014-09-25 17:30:22

标签: mysql sql date join timestamp

鉴于下面的DB Schema,我想加入time_data和weather:

每个城市都有一些电台,每分钟我都会在time_data行中保存一些关于电台的数据。

主要问题是我每2个小时都有天气信息,所以加入对我来说有点困难。

给定一个time_data我想找到天气行,其中有关于天气的最近(时间戳)信息 (即从所有时间戳都低于单个time_data的天气行中选择,具有最大时间戳的天气行)

所以最后我想为每个time_data行获取这些数据:

id,自行车,免费,时间戳,版本,电台,wind_chill,wind_direction,wind_speed

它应该是这样的,但我不知道如何真正实现它:

SELECT time_data.*, weather.*
FROM time_data
JOIN weather ON weather.timestamp = 
(SELECT max(weather.timestamp)
 FROM weather
 WHERE weather.timestamp<time_data.timestamp) <-- the time_data should be the same of the time_data row considered in the join
WHERE time_data.station=23
ORDER BY time_data.timestamp;

提前致谢!

Schema

1 个答案:

答案 0 :(得分:0)

我不知道MySQL,但我知道它有一个函数来计算两个日期之间的间隔。使用该函数,试试这个:

 Select case when IntervalFunc(wo.timestamp, td.timestamp) <
                  IntervalFunc(td.timestamp, w1.timestamp) 
             then w0.wind_Direction else w1.Wind_Direction end WIndDirection,
        case when IntervalFunc(wo.timestamp, td.timestamp) <
                  IntervalFunc(td.timestamp, w1.timestamp) 
             then w0.wind_Speed else w1.Wind_Speed end WIndSpeed,
    -- etc.
 from time_date td
    left join Weather w0 
       on w0.timestamp = (Select Max(timestamp)
                          From weather 
                          where timestamp < td.timestamp )
    left join weather w1
       on w0.timestamp = (Select Min(timestamp)
                          From weather 
                          where timestamp > td.timestamp
 Where td.Id = @someID )

或者,对于所有领域..​​....

Select * from Weather 
Where TimeStamp = 
    (Select case when IntervalFunc(wo.timestamp, td.timestamp) <
                  IntervalFunc(td.timestamp, w1.timestamp) 
             then w0.Timestamp else w1.Timestamp end 
     From time_date td
        left join Weather w0 
           on w0.timestamp = (Select Max(timestamp)
                              From weather 
                              where timestamp < td.timestamp )
        left join weather w1
           on w0.timestamp = (Select Min(timestamp)
                              From weather 
                              where timestamp > td.timestamp )
     Where td.Id = @someID )