【问题标题】:Retrieving mysql statistical data using PHP regular intervals and including null data使用PHP定期间隔检索mysql统计数据并包括空数据
【发布时间】:2012-01-05 07:27:40
【问题描述】:

所以我正在尝试为我的应用构建一些不错的统计数据显示。我可以这样做,因为我将命中统计信息保存在表格中。它只是跟踪点击次数以及其他一些不错的数据以及它发生的时间。我可以查询 db 以显示过去 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 天。

【问题讨论】:

  • 显然,如果表格中没有命中该日期,则选择不会返回任何内容

标签: php mysql statistics analytics


【解决方案1】:

您有 3 个选项:

  • 尝试在应用程序逻辑 (php) 中迭代日期
  • 生成一个(临时)表,里面填满您需要的日期,然后加入它
  • 使用in this answer之类的mysql存储过程解决方案

应用逻辑实现示例:

<?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);
    }

?>

【讨论】:

  • 感谢节目主持人!我找到了这些解决方案,但希望有更简单的方法。我觉得我错过了一些东西,因为迭代 180 多个日期并进行 180 个查询似乎很繁重。
  • 1 次查询,1 次迭代就足够了。 php 中的迭代获取您需要的所有日期,查询返回所有包含数据的行。在迭代中,打印出找到数据的位置,否则打印 0。
  • 如果您显示代码示例,对您来说很重要。大的!您有一个缺少日期的数组,以及用零填充缺失日期的天才函数。
猜你喜欢
  • 2012-02-18
  • 1970-01-01
  • 2011-03-10
  • 2012-06-09
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
  • 2012-04-27
  • 2012-07-27
相关资源
最近更新 更多