2013-10-14 69 views
2

代碼:是否可以使NULL而不是NULL顯示0?

SELECT 
    count(*) as count, 
    sum(Status = 'test1') as count_test1, 
    sum(Status = 'test2') as count_test2 
FROM Table 
WHERE Type = 'test' 

的結果,我看到:

count count_test1 count_test2 
    0  NULL   NULL 

請告訴我,纔有可能做出的,而不是NULL會顯示0?

P.S:這是結果:

count count_test1 count_test2 
    0  0    0 

回答

4

可以使用COALESCE

COALESCE(sum(Status = 'test1'), 0) 

IFNULL

IFNULL(sum(Status = 'test1'), 0) 
+1

使用'COALESCE(總和(狀態= 'TEST1'),0)作爲count_test1'? –

+0

是的,沒錯。 –

+0

非常感謝 - 11分鐘後我接受了(系統計算器的限制) –

1
SELECT 
    count(*) as count, 
     IFNULL(sum(Status = 'test1'), 0) as count_test1, 
     IFNULL(sum(Status = 'test2'), 0) as count_test2 
FROM Table 
WHERE Type = 'test' 
+0

我覺得在這種情況下IFNULL更具體。另外閱讀:http://stackoverflow.com/questions/4747877/mysql-ifnull-vs-coalesce-which-is-faster –

+0

@VincentTan我相信它是非常快一些,但我不得不承認不便攜。 – Fred

0

可以使用COALESCE函數採取一個數組並返回第一個元素不是空

SELECT 
    count(*) as count, 
    COALESCE(sum(Status = 'test1'), 0) as count_test1, 
    COALESCE(sum(Status = 'test2'), 0) as count_test2 
FROM Table 
WHERE Type = 'test' 
相關問題