每天分组填补空白

时间:2013-12-11 09:09:28

标签: mysql

我正在尝试根据本教程Using MySQL to generate daily sales reports with filled gaps为特定用户生成每日销售报告。 为此,我有三个表,记录表用户表日历表

records     user      calendar
id          id        datefield
user_id     
timestamp

下面的查询返回0作为total,并且当数据在特定日期不可用时,返回NULL作为user_id:

SELECT calendar.datefield AS DATE,
       IFNULL(COUNT(records.id),0) AS total, records.user_id
FROM records 
RIGHT JOIN calendar ON (DATE(records.timestamp) = calendar.datefield)    

WHERE ( 
    calendar.datefield BETWEEN (NOW() - INTERVAL 14 DAY) AND NOW()
)
GROUP BY DATE DESC

我们的想法是为特定用户生成此报告,因此我将上述查询修改为以下内容:

SELECT calendar.datefield AS DATE,
           IFNULL(COUNT(records.id),0) AS total, records.user_id
    FROM records 
    RIGHT JOIN calendar ON (DATE(records.timestamp) = calendar.datefield)

    WHERE ( 
        calendar.datefield BETWEEN (NOW() - INTERVAL 14 DAY) AND NOW()
        AND records.user_id = SOME_EXISTING_USER_ID
    )
    GROUP BY DATE DESC

当没有记录时返回空结果,但想法是在没有数据的任何特定日期返回0。

如何修改第一个查询以适合特定用户?

1 个答案:

答案 0 :(得分:5)

哇。自从我在野外见过RIGHT JOIN以来已经有一段时间了!无论如何,尝试将WHERE子句中的用户谓词添加到RIGHT JOIN中,如下所示:

SELECT calendar.datefield AS DATE,
           IFNULL(COUNT(records.id),0) AS total, records.user_id
    FROM records 
    RIGHT JOIN calendar ON (DATE(records.timestamp) = calendar.datefield) 
                        AND records.user_id = SOME_EXISTING_USER_ID

    WHERE ( 
        calendar.datefield BETWEEN (NOW() - INTERVAL 14 DAY) AND NOW()
    )
    GROUP BY DATE DESC;

对我而言,这是显式连接与隐式连接的巨大好处之一......