每当新访客访问我的网站时,他们都会登录到数据库中。通过使用以下查询,我已经能够选择过去7天内特定日期的用户数:

SELECT COUNT(*) AS Hits, DATE_FORMAT(Date, '%Y-%m-%d') AS HitDay FROM(stats) WHERE Date >= DATE_SUB(SYSDATE(), INTERVAL 7 DAY) GROUP BY DATE(Date) ORDER BY Date ASC


问题是作为项目的一部分,我必须将此数据绘制在VB内的图表中,并且如果在特定日期没有命中,则图表上的两个日期之间会有间隙。我想知道是否有可能返回过去7个日期中的所有日期,如果没有任何访问者,则在Hits列上返回0。时间间隔也可以更改,因此范围可以从1到31。

也许可以通过过程或功能来完成?任何想法都很棒,但是我试图不填补VB中的空白。

最佳答案

您可以生成7天,并使用以下统计信息将其左加入

SELECT COUNT(stats.date) AS Hits, DATE_FORMAT(days.Date, '%Y-%m-%d') AS HitDay
FROM
   (SELECT CURDATE() as date
    UNION SELECT CURDATE() - INTERVAL 1 DAY
    UNION SELECT CURDATE() - INTERVAL 2 DAY
    UNION SELECT CURDATE() - INTERVAL 3 DAY
    UNION SELECT CURDATE() - INTERVAL 4 DAY
    UNION SELECT CURDATE() - INTERVAL 5 DAY
    UNION SELECT CURDATE() - INTERVAL 6 DAY
    )days
LEFT JOIN stats ON days.date = stats.date
GROUP BY DATE(days.Date) ORDER BY days.Date ASC


sqlFiddle

如果您的间隔更改可能指定如下(最多128天),然后将条件< 7更改为您的间隔

SELECT COUNT(stats.date) AS Hits, DATE_FORMAT(days.Date, '%Y-%m-%d') AS HitDay
FROM
   (SELECT CURDATE() - INTERVAL
     (d1.value+d2.value+d3.value+d4.value+
      d5.value+d6.value+d7.value) day as date
    FROM (SELECT 0 as value UNION SELECT 1)d1,
         (SELECT 0 as value UNION SELECT 2)d2,
         (SELECT 0 as value UNION SELECT 4)d3,
         (SELECT 0 as value UNION SELECT 8)d4,
         (SELECT 0 as value UNION SELECT 16)d5,
         (SELECT 0 as value UNION SELECT 32)d6,
         (SELECT 0 as value UNION SELECT 64)d7
    WHERE (d1.value+d2.value+d3.value+d4.value+
      d5.value+d6.value+d7.value) < 7
    )days
LEFT JOIN stats ON days.date = DATE(stats.date)
GROUP BY DATE(days.Date) ORDER BY days.Date ASC


sqlFiddle

关于php - MySQL整天获取网站统计信息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21271056/

10-13 00:53