MySQL填空日期

时间:2015-03-30 15:54:03

标签: php mysql date

我一直试图解决这个问题一段时间后无法找到解决方案:我正在查询时间条目,结果如下:

2015-02-10: 13
2015-02-11: 16
2015-02-13: 11

正如您所看到的,我在数组中错过了两天,因为这些天没有条目。我的google-fu为我带来了一些解决这个问题的方法,但似乎没有一个能用于我的特定代码:

SELECT
    DATE(time_entries.start) AS date,
    COUNT(time_entries.id) AS entries,
    SUM(CASE WHEN user_id = 4 THEN TIMESTAMPDIFF(MINUTE, start, end) ELSE 0 END) AS me,
    SUM(CASE WHEN user_id = 3 THEN TIMESTAMPDIFF(MINUTE, start, end) ELSE 0 END) AS ph
    FROM time_entries
    LEFT JOIN calendar_table
    ON time_entries.start=calendar_table.dt
    WHERE start BETWEEN CURRENT_DATE - INTERVAL 1 MONTH AND CURDATE()
    GROUP BY date
    ORDER BY date

我使用此帮助创建了calendar_table:https://www.brianshowalter.com/calendar_tables

请帮忙! 最好, 克里斯

1 个答案:

答案 0 :(得分:0)

尝试正确加入。您的查询使用您的time_entries记录来匹配日历表,并且找不到任何内容,因为它们不在那里。

通过使用右连接,您将首先使用calendar_table记录。

SELECT
    DATE(time_entries.start) AS date,
    COUNT(time_entries.id) AS entries,
    SUM(CASE WHEN user_id = 4 THEN TIMESTAMPDIFF(MINUTE, start, end) ELSE 0 END) AS me,
    SUM(CASE WHEN user_id = 3 THEN TIMESTAMPDIFF(MINUTE, start, end) ELSE 0 END) AS ph
    FROM time_entries
    RIGHT JOIN calendar_table
    ON time_entries.start=calendar_table.dt
    WHERE start BETWEEN CURRENT_DATE - INTERVAL 1 MONTH AND CURDATE()
    GROUP BY date
    ORDER BY date