2013-12-11 61 views
0

我試圖根據本教程Using MySQL to generate daily sales reports with filled gaps爲特定用戶生成每日銷售報告。 要做到這一點,我有三個表,記錄表用戶表日曆表按天填寫空白組

records  user  calendar 
id   id  datefield 
user_id  
timestamp 

下面將返回0作爲總的和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。

如何修改爲特定用戶工作的第一個查詢?

回答

3

哇。過了一段時間,因爲我已經在野外看到了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; 

對我來說,這是明確的巨大好處之一加入VS隱加入...

+0

我不斷地學習。 ..真棒!謝謝 – Lomse