gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:54:41 25 4
gpt4 key购买 nike

我想计算每天的帖子数量以创建图表。我的问题是,由于 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

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

最佳答案

您可以通过日期表来解决此问题,执行 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

对于日期表,我使用以下帖子中的方法:generate days from date range

关于php - 如何在 while 循环中回显没有结果的日子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291809/

25 4 0