2012-06-07 57 views
2

我有如下表:IFNULL不工作的MySQL

 
+----+------------+----------+------------------+ 
| id | created_at | platform | platform_version | 
+----+------------+----------+------------------+ 
| 1 |   1 | mac  | 1    | 
| 2 |   2 | mac  | 1    | 
| 3 |   3 | mac  | 2    | 
| 4 |   4 | mac  | 2    | 
| 5 |   5 | mac  | 2    | 
| 6 |   5 | mac  | 3    | 
| 7 |   2 | windows | 1    | 
| 8 |   2 | windows | 2    | 
| 9 |   3 | windows | 3    | 
| 10 |   3 | windows | 1    | 
| 11 |   4 | windows | 2    | 
| 12 |   4 | windows | 3    | 
| 13 |   5 | windows | 4    | 
| 14 |   5 | windows | 1    | 
| 15 |   6 | windows | 2    | 
| 16 |   6 | windows | 3    | 
+----+------------+----------+------------------+ 

我想有一個像下面這樣的結果:

 
+-------------+---------------+---------------+------------+ 
| group_count | running_total | windows_total | created_at | 
+-------------+---------------+---------------+------------+ 
|   1 |    1 |    0 |   1 | 
|   6 |    7 |    4 |   2 | 
|   7 |   14 |    8 |   4 | 
|   2 |   16 |   10 |   6 | 
+-------------+---------------+---------------+------------+ 

但是,當我執行此select語句:

 
SELECT group_count, 
     (@r := @r + group_count) AS running_total, 
     (@w := @w + ifnull(win_count, 0)) AS windows_total, 
     t1.created_at 
FROM (SELECT (@r :=0), 
       COUNT(*) AS group_count, 
       platform, 
       created_at 
     FROM  devices 
     GROUP BY created_at DIV 2 
    ) AS t1 LEFT JOIN 
     (SELECT COUNT(*) AS win_count, 
       created_at 
     FROM  devices 
     WHERE platform = 'windows' 
     GROUP BY created_at DIV 2 
    ) AS t3 ON t1.created_at = t3.created_at 

它是這樣出現的:

 
+-------------+---------------+---------------+------------+ 
| group_count | running_total | windows_total | created_at | 
+-------------+---------------+---------------+------------+ 
|   1 |    1 |   NULL |   1 | 
|   6 |    7 |   NULL |   2 | 
|   7 |   14 |   NULL |   4 | 
|   2 |   16 |   NULL |   6 | 
+-------------+---------------+---------------+------------+ 

coalesce也不起作用。誰能幫忙?謝謝。

+3

'@ w'最初是'NULL',因此將其添加到'IFNULL'的結果中(無論結果如何)都會產生NULL。在子選項中給它一個初始值,就像你用'@ r'完成的那樣。 – eggyal

+0

d'oh。感謝那。我沒有注意到這一點。 – luis

+0

@eggyal,這應該是一個答案,而不是評論。 – Johan

回答

0

爲了記錄在案,我引用@ eggyal的回答是:

@w最初是NULL,所以將它添加到IFNULL的結果(不管這結果)產生NULL。
給它一個初始值的子查詢,爲您與@r

SELECT group_count, 
     (@r := @r + group_count) AS running_total, 
     (@w := @w + ifnull(win_count, 0)) AS windows_total, 
     t1.created_at 
FROM (SELECT (@r:= 0),(@w:= 0), 
       COUNT(*) AS group_count, 
       platform, 
       created_at 
     FROM  devices 
     GROUP BY created_at DIV 2 
    ) AS t1 LEFT JOIN 
     (SELECT COUNT(*) AS win_count, 
       created_at 
     FROM  devices 
     WHERE platform = 'windows' 
     GROUP BY created_at DIV 2 
    ) AS t3 ON t1.created_at = t3.created_at 

這樣做應該解決這個問題。