2016-02-01 71 views
1

我的問題是根據他們的肌酸年份和月份從數據庫中選擇記錄計數。我有這樣的MySQL查詢:選擇零發生的月度計數

SELECT year, m, month, COUNT(bans.ban_id) AS total 
FROM (
    SELECT year, m, month 
    FROM 
    (SELECT YEAR(CURDATE()) year UNION ALL SELECT YEAR(CURDATE())-1) years, 
    (
     SELECT 1 m, 'Jan' month 
     UNION ALL SELECT 2 m, 'Feb' month 
     UNION ALL SELECT 3 m, 'Mar' month 
     UNION ALL SELECT 4 m, 'Apr' month 
     UNION ALL SELECT 5 m, 'May' month 
     UNION ALL SELECT 6 m, 'Jun' month 
     UNION ALL SELECT 7 m, 'Jul' month 
     UNION ALL SELECT 8 m, 'Aug' month 
     UNION ALL SELECT 9 m, 'Sep' month 
     UNION ALL SELECT 10 m, 'Oct' month 
     UNION ALL SELECT 11 m, 'Nov' month 
     UNION ALL SELECT 12 m, 'Dec' month 
    ) months 
) ym 
LEFT JOIN bans 
    ON ym.year = YEAR(bans.ban_created_at) 
    AND ym.m = MONTH(bans.ban_created_at) 
WHERE 
    (year=YEAR(CURDATE()) AND m<=MONTH(CURDATE())) 
    OR 
    (year<YEAR(CURDATE()) AND m>MONTH(CURDATE())) 
    AND 
    (ban_banlist_id = 13) 
GROUP BY year, m 

據工作幾乎是正常的,但 - 問題是,查詢返回只記錄有效的計數值 - 例如當月份沒有記錄時,不返回。請問你能幫幫我嗎? :)

感謝,
TheKronnY

回答

0

的原因是,在右表中的狀態(禁令)是在WHERE子句,因此它的結果應用,用的效果,只有一個月出現次數會被選中。把它放在LEFT JOIN子句中的ON子句,像這樣:

SELECT year, m, month, COUNT(bans.ban_id) AS total 
FROM (
    SELECT year, m, month 
    FROM 
    (SELECT YEAR(CURDATE()) year UNION ALL SELECT YEAR(CURDATE())-1) years, 
    (
     SELECT 1 m, 'Jan' month 
     UNION ALL SELECT 2 m, 'Feb' month 
     UNION ALL SELECT 3 m, 'Mar' month 
     UNION ALL SELECT 4 m, 'Apr' month 
     UNION ALL SELECT 5 m, 'May' month 
     UNION ALL SELECT 6 m, 'Jun' month 
     UNION ALL SELECT 7 m, 'Jul' month 
     UNION ALL SELECT 8 m, 'Aug' month 
     UNION ALL SELECT 9 m, 'Sep' month 
     UNION ALL SELECT 10 m, 'Oct' month 
     UNION ALL SELECT 11 m, 'Nov' month 
     UNION ALL SELECT 12 m, 'Dec' month 
    ) months 
) ym 
LEFT JOIN bans 
    ON ym.year = YEAR(bans.ban_created_at) 
    AND ym.m = MONTH(bans.ban_created_at) 
    AND ban_banlist_id = 13 
WHERE 
    (year=YEAR(CURDATE()) AND m<=MONTH(CURDATE())) 
    OR 
    (year<YEAR(CURDATE()) AND m>MONTH(CURDATE())) 
GROUP BY year, m 
+0

它完美,非常感謝。 :)你能簡單解釋一下爲什麼? – TheKronnY

+0

如果你在左連接的右邊表格的where子句上添加一個條件(在這裏禁止),它只會選擇那些有禁止的行(這裏id = 13),所以最後你只會有id = 13的禁令的結果,如果沒有發生,則沒有任何結果。所以爲此,如果右表(禁止)存在條件,則將其置於ON子句中。 –

+0

明白了!謝謝! ^^ – TheKronnY