且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL如何填充范围内缺少的小时/日期?

更新时间:2021-11-13 05:17:41

不是最漂亮的.但是,如果您真的不能使用临时表,它应该可以解决问题:

Not the prettiest. But it should do the trick if you really can't use temp tables:

select ifnull(count,0) as count,dh.hour_of_day,
dh.day_of_week,date_format((date('2012-01-02') + interval dh.day_of_week day),'%W') as name_of_day
from
(
select day_of_week,hour_of_day
from 
(
 select 0 as day_of_week union select 1 union select 2 union select 3 
 union select 4 union select 5 union select 6
) d
 join
(
 select 0 as hour_of_day 
 union select 1 union select 2 union select 3 union select 4 
 union select 5 union select 6 union select 7 union select 8
 union select 9 union select 10 union select 11 union select 12
 union select 13 union select 14 union select 15 union select 16
 union select 17 union select 18 union select 19 union select 20
 union select 21 union select 22 union select 23
) h
) dh
left outer join
(
SELECT
count(id) as count,
HOUR(created) as hour_of_day,
WEEKDAY(created) as day_of_week,
DATE_FORMAT(created,'%W') name_of_day
FROM visitors
GROUP BY day_of_week,hour_of_day
) v on dh.day_of_week = v.day_of_week and dh.hour_of_day = v.hour_of_day
ORDER BY dh.day_of_week,dh.hour_of_day ASC; 

但是请小心!如果您跨多个星期运行查询,那么一周中的多个天会加在一起.您可能需要考虑添加仅本周"谓词.例如,将where yearweek(created) = yearweek(now())添加到原始选择中即可获取当前一周的数据.

Careful with this though! If you run the query across multiple weeks then multiple days of the week will get added together. You may want to consider adding a 'only this week' predicate. For example add in where yearweek(created) = yearweek(now()) into your original select to get data just for the current week.