我希望每24小时获得一次转换报告。 我有这个查询,但它只返回19个而不是24个 任何人都可以告诉我这个错误吗? 提前谢谢。
SELECT HOUR( `date_time` ) AS Hours, COUNT(conversion_id) AS `conversion` FROM conversions
RIGHT JOIN (SELECT 0 AS Hour 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 UNION ALL SELECT 10 UNION ALL SELECT 11
UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL
SELECT 18 UNION ALL SELECT 19 UNION ALL SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23) AS AllHours
ON HOUR(date_time) = Hour
WHERE DATE(date_time) = CURDATE() OR date_time IS NULL
GROUP BY Hour
ORDER BY Hour
答案 0 :(得分:1)
如果此时间没有条目,则永远不会选中。你必须反过来查询。
我认为它应该是这样的(没有你的数据库很难测试):
select * from (SELECT 0 AS Hour 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 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23) as AllHours
left outer join
(select COUNT(conversion_id) as cnt, HOUR(date_time) as h
FROM conversions
WHERE DATE(date_time) = CURDATE() OR date_time IS NULL
group by h) as c
on Hour = e.h
答案 1 :(得分:0)
right join
几乎是正确的。我更喜欢where
条件中的on
条件(而不是检查NULL
个值。但是,关键是使用{{1}中的AllHours
表}和select
:
group by