每天计算MySQL条目,包括几天没有任何条目(日期范围)

时间:2015-06-23 11:06:28

标签: php mysql

我有一个MySQL-Table

id     mydate         content
----------------------------------
1      2015-06-20     some content
2      2015-06-20     some content
3      2015-06-22     some content

现在我想计算每一天的条目:

SELECT DATE(mydate) Date, COUNT(DISTINCT id) dayCount FROM mytable
GROUP BY DATE(mydate) HAVING dayCount > -1 ORDER BY DATE(mydate) DESC

这对我有用,结果:

2015-06-20 = 2
2015-06-22 = 1

如何在没有任何条目的情况下获取天数?在我的例子中,结果应该是:

2015-06-19 = 0
2015-06-20 = 2
2015-06-21 = 0
2015-06-22 = 1
2015-06-23 = 0

基于此:

<?php
$today = date("Y-m-d");
$mystartdate = date_create($today);
date_sub($mystartdate, date_interval_create_from_date_string('14 days'));
$mystartdate = date_format($mystartdate, 'Y-m-d');
?>

最后我想输出过去14天的计数,也是“0天”。希望你能理解我的问题。

2 个答案:

答案 0 :(得分:0)

为此你可以创建一个包含增量数字的新表,但这不是一个好主意。但是,如果这样做,请使用此表使用DATE_ADD构造日期列表。

根据时间部分左键加入您的数据表以获得日期列表

了解更多信息请点击链接

MySQL how to fill missing dates in range?

答案 1 :(得分:0)

尝试以下 -

SELECT a.date_field, COUNT(DISTINCT b.id) dayCount FROM 
(SELECT date_field FROM
(
    SELECT
        MAKEDATE(YEAR(NOW()),1) +
        INTERVAL (MONTH(NOW())-1) MONTH +
        INTERVAL daynum DAY date_field
    FROM
    (
        SELECT t*10+u daynum
        FROM
            (SELECT 0 t UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) A,
            (SELECT 0 u UNION SELECT 1 UNION SELECT 2 UNION SELECT 3
            UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
            UNION SELECT 8 UNION SELECT 9) B
        ORDER BY daynum
    ) AA
) AAA
WHERE MONTH(date_field) = MONTH(NOW()) ) a 
LEFT JOIN mytable b ON a.date_field=DATE(b.mydate) 
GROUP BY a.date_field HAVING dayCount > -1 ORDER BY a.date_field DESC;