Virik Virik - 13 days ago 5
MySQL Question

MySQL One row for each hour of the day

I'm trying to get one row for each hour of the day, which I intent to left join certain data to.

So far I have only found this solution, but I'm pretty sure it's easier ways to do this..?

SElECT addtime('2016-01-22 00:00:00', t0.i) myHour
FROM (
SELECT '00:00:00' i
UNION SELECT '01:00:00'
UNION SELECT '02:00:00'
UNION SELECT '03:00:00'
UNION SELECT '04:00:00'
UNION SELECT '05:00:00'
UNION SELECT '06:00:00'
UNION SELECT '07:00:00'
UNION SELECT '08:00:00'
UNION SELECT '09:00:00'
UNION SELECT '10:00:00'
UNION SELECT '11:00:00'
UNION SELECT '12:00:00'
UNION SELECT '13:00:00'
UNION SELECT '14:00:00'
UNION SELECT '15:00:00'
UNION SELECT '16:00:00'
UNION SELECT '17:00:00'
UNION SELECT '18:00:00'
UNION SELECT '19:00:00'
UNION SELECT '20:00:00'
UNION SELECT '21:00:00'
UNION SELECT '22:00:00'
UNION SELECT '23:00:00'
) t0

Answer

this is only a little bit smaler:

SELECT '2016-01-22 00:00:00' + INTERVAL (d0*10+d1) hour  AS mydate
FROM (
SELECT 0 AS d0 UNION SELECT 1 UNION SELECT 2
) AS t1
cross JOIN (
SELECT 0 AS d1 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 ) AS t2
WHERE (d0*10+d1) < 24
order by d0,d1;

but!!, if you can use MariaDB you can use the sequence Engine and do it like this:

 SELECT '2016-01-22 00:00:00' + INTERVAL seq HOUR as mydate from seq_0_to_23;

mydate
2016-01-22 00:00:00
2016-01-22 01:00:00
2016-01-22 02:00:00
2016-01-22 03:00:00
2016-01-22 04:00:00
2016-01-22 05:00:00
2016-01-22 06:00:00
2016-01-22 07:00:00
2016-01-22 08:00:00
2016-01-22 09:00:00
2016-01-22 10:00:00
2016-01-22 11:00:00
2016-01-22 12:00:00
2016-01-22 13:00:00
2016-01-22 14:00:00
2016-01-22 15:00:00
2016-01-22 16:00:00
2016-01-22 17:00:00
2016-01-22 18:00:00
2016-01-22 19:00:00
2016-01-22 20:00:00
2016-01-22 21:00:00
2016-01-22 22:00:00
2016-01-22 23:00:00