2017-03-09 87 views
1

所以我在MySQL中有一個表PowerUse。它有兩個重要的列,ID(long int)和timeRecorded(timeStamp)。條目之間通常有很長的時間差距。我的目標是查詢表格以得到一個結果,告訴我在20分鐘內每分鐘有多少記錄 - 包括沒有記錄的分鐘的0響應。SQL JOIN語法問題

感謝MySQL: Select All Dates In a Range Even If No Records Present我已經到了下面的查詢,但我不能得到dratted的工作。有人能指出我正在製造的明顯錯誤,所以我可以停止將我的頭撞在磚牆上嗎?我知道它在JOIN中,我看不到它。謝謝!

select count(PowerUse.id) + 0 as counter, timestamp((PowerUse.timeRecorded div 100)*100) as time 
from PowerUse right join  
(
select date_add(NOW(), INTERVAL -n2.num*10-n1.num MINUTE) as dateb from 
(select 0 as num 
    union all select 1 
    union all select 2 
    union all select 3 
    union all select 4 
    union all select 5 
    union all select 6 
    union all select 7 
    union all select 8 
    union all select 9) n1, 
(select 0 as num 
    union all select 1 
    union all select 2 
) n2 
as) datea 

on (timestamp(PowerUse.timeRecorded div 100)*100) = dateb.datea 
    group by timeRecorded div 100 ; 

回答

1

我想你最好的選擇是創建另一個表:

  • 起始日期
  • END_DATE

,並與你的範圍內填充....

那麼你可以加入:

select start_date, count(PowerUse.id) + 0 as counter, timestamp((PowerUse.timeRecorded div 100)*100) as time 
from PowerUse 
right join timeframes on ( timestamp((PowerUse.timeRecorded div 100)*100) >= start_date and timestamp((PowerUse.timeRecorded div 100)*100) < end_date) 
group by start_date 

類似的東西