Bukan yang tercantik. Tetapi itu akan berhasil jika Anda benar-benar tidak dapat menggunakan tabel temp:
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;
Hati-hati dengan ini! Jika Anda menjalankan kueri selama beberapa minggu, maka beberapa hari dalam seminggu akan ditambahkan bersama-sama. Anda mungkin ingin mempertimbangkan untuk menambahkan predikat 'hanya minggu ini'. Misalnya tambahkan where yearweek(created) = yearweek(now())
ke pilihan asli Anda untuk mendapatkan data hanya untuk minggu ini.