2016-07-12 52 views
0

我有一個標準表的用戶列表和我有一列lastactivity與UNIX時間戳(這表明當他們登錄)和列timestamp與UNIX時間戳顯示他們何時註冊。MySQL的函數IFNULL不是GROUP BY工作

我已經建立一個SQL查詢,顯示有多少用戶通過使計數器的計數值有多少用戶每星期登記的周從現在起24小時(86400秒)和分組結果中表現積極:

SELECT 
    IFNULL(COUNT(*),0) as `counter`, 
    (WEEK(`timestamp`)) as `week` 
FROM 
    `clients` 
WHERE 
    (CAST(UNIX_TIMESTAMP() as signed) - CAST(`lastactivity` as signed)) <= 86400 
GROUP BY 
    WEEK(`timestamp`); 

問題是功能IFNULL(COUNT(*),0)不按我的意圖工作。如果在計數器上存在NULL/0,即使使用MySQL函數,此SQL查詢也不會顯示星期。這可能是因爲GROUP BY的工作原理。因此,例如,我會得到這樣的結果:

counter | week 
    2 | 11 
    1 | 13 
    9 | 14 
    6 | 17 

但我想,以顯示每星期是這樣的:

counter | week 
    2 | 11 
    0 | 12 
    1 | 13 
    9 | 14 
    0 | 15 
    0 | 16 
    6 | 17 

任何人有任何想法,我怎麼能解決這個問題?

戈登試圖通過讓LEFT JOIN查詢來幫助我,但我還是得到了相同的結果,也許我在這裏做得不對:

SELECT 
    COUNT(a.id) as `counter`, 
    (WEEK(b.timestamp)) as `week` 
FROM 
    `users` a 
LEFT JOIN 
    `users` b 
ON 
    a.id = b.id 
WHERE 
    (CAST(UNIX_TIMESTAMP() as signed) - CAST(a.lastactivity as signed)) <= 86400 
GROUP BY 
    WEEK(b.timestamp); 
+0

這實際上是一個顯示問題 - 因此,如果可用,最好在表示層中處理。 – Strawberry

回答

1

這是太長了評論。

問題是你不明白查詢是如何工作的。 IFNULL()(或標準版COALESCE()轉換一個值爲NULL爲其他值然而,COUNT()永遠不會返回NULL所以,離開它:。

SELECT COUNT(*) as `counter`, WEEK(`timestamp`) as `week` 
FROM `clients` 
WHERE (CAST(UNIX_TIMESTAMP() as signed) - CAST(`lastactivity` as signed)) <= 86400 
GROUP BY WEEK(`timestamp`); 

您的問題是缺少行,不NULL值你將有一個LEFT JOIN解決這個

編輯:

你需要一個left join包括所有周:

SELECT COUNT(c.timestamp) as `counter`, wk as `week` 
FROM (SELECT 11 as wk UNION ALL 
     SELECT 12 UNION ALL 
     SELECT 13 UNION ALL 
     SELECT 14 UNION ALL 
     SELECT 15 UNION ALL 
     SELECT 16 UNION ALL 
     SELECT 17 
    ) w LEFT JOIN 
    `clients` c 
    ON WEEK(c.`timestamp`) = w.wk 
WHERE (CAST(UNIX_TIMESTAMP() as signed) - CAST(`lastactivity` as signed)) <= 86400 
GROUP BY WEEK(`timestamp`); 
+0

我正在嘗試'LEFT JOIN',但仍然無法正常工作。你能檢查我的SQL查詢嗎? –