创建使用日期填充的临时表,并将LEFT JOIN连接到`created_at`列 - MySQL

时间:2014-01-22 20:52:39

标签: mysql

原始查询:

// Doesn't return dates with zero value

SELECT UNIX_TIMESTAMP( created_at ) AS DATE, COUNT( tweet_id ) AS count
FROM  `tweets` 
WHERE DATE( created_at ) >  '2012-11-01'
AND DATE( created_at ) <= DATE( NOW( ) ) 
GROUP BY DATE

修改后的查询:

// Attempting to return all dates with a value of zero if doesn't exist in `created_at` column

CREATE TEMPORARY TABLE DateSummary1 ( date timestamp ) SELECT DISTINCT(DATE(created_at)) as date FROM tweets;
CREATE TEMPORARY TABLE DateSummary2 ( date timestamp, number int ) SELECT DATE(created_at) as date, count(*) AS number FROM tweets WHERE DATE(created_at) > '2012-11-01' AND DATE(created_at) <= DATE(NOW()) GROUP BY DATE(created_at) ORDER BY created_at ASC;
SELECT ds1.date,ds2.number FROM DateSummary1 ds1 LEFT JOIN DateSummary2 ds2 on ds1.date=ds2.date;

不幸的是,后者的结果并没有像我预期的那样为我提供零值的日期。我在俯瞰什么?我确定这是一个逻辑错误,但我不确定我的逻辑出了什么问题。我已经远远没有阅读SO,Google等上的大量帖子了,但我不确定如何克服这个最后的障碍。

使用jcho360的建议返回时间戳的示例:

1387286811
1387286812
1387286813
1387286815
1387286820

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT UNIX_TIMESTAMP( created_at ) AS DATE, COUNT( tweet_id ) AS count
FROM  `tweets` 
WHERE (DATE( created_at ) >  '2012-11-01'
AND DATE( created_at ) <= DATE( NOW( ) ) )
or DATE( created_at ) = date ('000-00-00') //I added this Line
GROUP BY DATE