2014-09-25 31 views
0

下面給出了DB模式的日期,我想加入time_data與天氣:SQL加入上有微弱的關係

每個城市都有一些車站和每分鐘我節省約在time_data排站的一些數據。

主要問題是我每2小時收到一次天氣信息,因此加入對我來說有點困難。

給定一個單一的time_data我想找到最近的天氣行(時間戳記)關於天氣的信息 (即從所有天氣行中選擇時間戳低於單個time_data ,具有最大時間戳的一個)

所以最後我想獲得這些數據對每個time_data行:

ID,自行車,免費,時間戳,版本,車站,wind_chill, - 風向,風速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

回答

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)