0

我想计算每天的帖子数量以创建图表。我的问题是,由于 SQL 几天没有找到结果(计数为 0),我缺少图表所需的行(因为我确实想显示没有帖子的日子)。

SELECT DATE(Date) AS Day, COUNT(*) AS COUNT 
FROM `Posts` 
GROUP By `Day`
ORDER BY Date DESC

while($row = mysql_fetch_array($result)) {
    echo $row['Date'] . ": " . $row['Count'];
    }

由于循环不显示结果为 0 的天数,因此如果在星期三没有我收到的帖子:monday-17-3: 5, tuesday-18-3: 2, thursday-20-3: 3. 相反,我想填写空白,所以我得到类似:wednesday-19-3: 0.

如何在循环中回显没有结果的日子?

4

2 回答 2

2

您可以通过日期表解决此问题,执行OUTER JOIN,然后执行分组。这将为您提供两者之间的日期(免责声明:我假设您的日期格式为 YYYY-MM-DD,否则您可能需要稍微调整 JOIN 语句。)。

SELECT A.Date AS Day, COUNT(Posts.Date) AS COUNT 
FROM 
   (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
    from (select 0 as a 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) as a
    cross join (select 0 as a 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) as b
    cross join (select 0 as a 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) as c
) A
LEFT OUTER JOIN `Posts` ON A.Date = `Posts`.`Date`
WHERE A.Date >= DATE_ADD(CURDATE(), INTERVAL -15 DAY)
GROUP BY A.Date

对于日期表,我使用以下帖子中的方法:从日期范围生成天数

于 2012-04-24T04:49:55.843 回答
0

使用循环遍历连续日期,使用如下函数:

$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");

对于每个周期,应用您的查询结果。然后你会得到所有的日期。

于 2012-04-24T04:50:59.923 回答