所以这是我的问题:
SELECT
COUNT( user_id ) AS `Records` ,
DATE( FROM_UNIXTIME( `tstamp` ) ) AS `Date`
FROM `user`
WHERE FROM_UNIXTIME('tstamp') >= '2014-11-00'
GROUP BY DATE( FROM_UNIXTIME( `tstamp` ) )
LIMIT 200
问题是它只返回大于0的记录数的行。是否有办法包括count = 0的日期?
答案 0 :(得分:1)
您可以在子查询中生成自己的日历表
SET @start_date = '2014-11-01';
SELECT MyData.dt,IFNULL(MyData.Records,0) Records FROM
(
SELECT dt FROM
(SELECT num,(@start_date + INTERVAL num DAY) dt FROM
(SELECT h*100+t*10+u num FROM
(SELECT 0 h 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) A,
(SELECT 0 t 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) B,
(SELECT 0 u 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) C) AA) AAA
WHERE dt <= DATE(NOW())
ORDER BY num
) Calendar LEFT JOIN
(
SELECT
COUNT(user_id) AS `Records` ,
DATE(FROM_UNIXTIME(`tstamp`)) dt
FROM `user`
WHERE FROM_UNIXTIME('tstamp') >= '2014-11-00'
GROUP BY DATE(FROM_UNIXTIME(`tstamp`))
LIMIT 200
) MyData USING (dt);
试一试!!!
CAVEAT:这个日历子查询仅在999天前完成。
您可以像这样延长9999天
SET @start_date = '2014-11-01';
SELECT MyData.dt,IFNULL(MyData.Records,0) Records FROM
(
SELECT dt FROM
(SELECT num,(@start_date + INTERVAL num DAY) dt FROM
(SELECT th*1000+h*100+t*10+u num FROM
(SELECT 0 th 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) Z,
(SELECT 0 h 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) A,
(SELECT 0 t 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) B,
(SELECT 0 u 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) C) AA) AAA
WHERE dt <= DATE(NOW())
ORDER BY num
) Calendar LEFT JOIN
(
SELECT
COUNT(user_id) AS `Records` ,
DATE(FROM_UNIXTIME(`tstamp`)) dt
FROM `user`
WHERE FROM_UNIXTIME('tstamp') >= '2014-11-00'
GROUP BY DATE(FROM_UNIXTIME(`tstamp`))
LIMIT 200
) MyData USING (dt);