【问题标题】:Mysql get count of rows for each dayMysql获取每天的行数
【发布时间】:2009-11-16 03:29:58
【问题描述】:

我当前的查询是:

SELECT DISTINCT DATE(vote_timestamp) AS Date, COUNT(*) AS TotalVotes FROM `votes` 
WHERE vote_target_id='83031'
GROUP BY DATE(vote_timestamp) ORDER BY DATE(vote_timestamp) DESC LIMIT 30

(为了便于阅读,换行符分开)

其中 vote_timestamp 是每个“投票”的时间,Count(*) 是当天的计数,vote_target_id 是投票的具体目标。

目前,这适用于目标至少有一个“投票”的所有日子,但我希望它在没有投票的日子里也将 TotalVotes 返回为 0,而不是根本没有行。

这(以及如何?)可以在 MySQL 或 PHP 中完成吗? (两者都可以,因为它由 PHP 进一步处理,因此可以使用任何代码)。

谢谢

【问题讨论】:

    标签: mysql date count days


    【解决方案1】:

    问题是如何为没有行的日期生成记录。 This SO question 有一些方法。

    【讨论】:

      【解决方案2】:

      查看that 解决方案,对我来说,执行此快速修复工作要简单得多。

      $result = mysql_query($sql) or die('Internal Database Error');
      if (mysql_num_rows($result) == 0) { return false; }
      while($row = mysql_fetch_assoc( $result )) {
          $votes[$row['Date']] = $row['TotalVotes'];
      }
      // fill 0s with php rather than using mysql
      $dates = array_keys($votes);
      for ($t = strtotime($dates[count($dates)-1]); $t <= time(); $t +=86400) {
          $date = date('Y',$t).'-'.date('m',$t).'-'.date('d',$t);
          if (!array_key_exists($date,$votes)) {
              $votes[$date] = 0;
          }
      }
      

      谢谢,

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-29
        • 1970-01-01
        • 2022-09-25
        • 1970-01-01
        • 2021-06-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多