P粉4329300812023-08-31 09:26:55
or
WITH RECURSIVE cte AS ( SELECT 0 `hour` UNION ALL SELECT `hour` + 1 FROM cte WHERE `hour` < 23 ) SELECT cte.`hour`, COUNT(test.id) `count` FROM cte LEFT JOIN test ON cte.`hour` >= HOUR(test.start_at) AND cte.`hour` < HOUR(test.end_at) GROUP BY 1 ORDER BY 1;
or
WITH RECURSIVE cte AS ( SELECT CAST('00:00:00' AS TIME) `hour` UNION ALL SELECT `hour` + INTERVAL 1 HOUR FROM cte WHERE `hour` < '23:00:00' ) SELECT cte.`hour`, COUNT(test.id) `count` FROM cte LEFT JOIN test ON cte.`hour` >= test.start_at AND cte.`hour` < test.end_at GROUP BY 1 ORDER BY 1;
The first query returns the hour column in time format, while the second query returns this column in numeric form. Choose the variant that is safe for you.
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5a77b6e3158be06c7a551cb7e64673de