php - 使用 PHP 定期检索 mysql 统计数据并包括空数据

标签 php mysql statistics analytics

所以我正在尝试为我的应用构建一些不错的统计显示。我可以这样做是因为我在表格中保留了命中统计数据。它只是跟踪命中加上一些其他不错的数据以及它发生的时间。我可以查询数据库以显示在特定日期或过去 x 天的每一天发生了多少次点击,如下面的代码所示。但是下面的代码只返回有数据的日期。我想显示最近 30 天的点击率,而不管一天是否有点击率。想法?

SELECT DATE(time) AS theday, COUNT( * ) AS thecount
FROM stats
WHERE time <= curdate( )
AND time >= DATE_SUB( curdate(), INTERVAL 30 DAY )
GROUP BY theday ORDER BY time DESC

生产

theday  thecount
2011-11-22  5
2011-11-21  9
2011-11-18  10
2011-11-16  1
2011-11-11  2
2011-11-10  15
2011-11-09  2
2011-10-26  1
2011-10-24  6

如您所见,它跳过了没有结果的日期。我明白为什么会这样,因为数据库中没有包含这些日期的行。我想知道如何生成一个查询,它的工作方式几乎与上述类似,但具有所述间隔的所有日期。 IE:最近 30 天。

最佳答案

您有 3 个选择:

  • 尝试在应用程序逻辑 (php) 中迭代日期
  • 生成一个(临时)表,其中包含您需要的日期并与之相连
  • 使用mysql存储过程解决方案,如in this answer

应用逻辑实现示例:

<?php

    date_default_timezone_set('Europe/Paris');

    $startdate = strtotime('2011-11-01 00:00:01');
    $days = 60;

    $found_data = array( // this is generated by 1 mysql query
        array('date_field' => '2011-11-02', 'count' => 5),
        array('date_field' => '2011-11-03', 'count' => 1),
        array('date_field' => '2011-11-04', 'count' => 6),
        array('date_field' => '2011-11-08', 'count' => 9),
        array('date_field' => '2011-11-09', 'count' => 3),
        array('date_field' => '2011-11-10', 'count' => 5),
        array('date_field' => '2011-11-12', 'count' => 1),
        array('date_field' => '2011-11-15', 'count' => 1),
        array('date_field' => '2011-11-18', 'count' => 4),
        array('date_field' => '2011-11-21', 'count' => 9),
        array('date_field' => '2011-11-23', 'count' => 1),
        array('date_field' => '2011-11-28', 'count' => 8),
        array('date_field' => '2011-11-30', 'count' => 6),
    );

    foreach ($found_data as $counts) { // we convert the results to a usable form, you can do this in the query, too
        $count_info[$counts['date_field']] = $counts['count'];
    }

    for ($i = 0; $i <= $days; $i++) {
        $date = date('Y-m-d', $startdate+$i*60*60*24);
        printf("%s\t%s\n", $date, array_key_exists($date, $count_info) ? $count_info[$date] : 0);
    }

?>

关于php - 使用 PHP 定期检索 mysql 统计数据并包括空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8251775/

相关文章:

php - 使用 PHP exec Wget 下载文件

MySQL "0 or 1"CSV 文件中的列导入为 "127"

php - 从结果集中删除避免重复项

statistics - "number of std deviations"远离均值的正确术语是什么

mysql - 存储点击和查看统计信息的最佳方式?

php - .htaccess 在 Linux 上不工作

php - 模型验证中的 Phalcon 可选字段

PHP if ($_POST) 的烦恼

mysql - 使用存储过程插入多个值

r - 在 R 中,如何估算低于检测限的左删失数据?