2012-01-17 56 views
18

我需要編寫一個查詢返回所有滿足特定條件的值的總和,但如果沒有找到行,查詢需要返回0而不是null。例如:如何選擇總和 - 或 - 0如果沒有記錄存在?

tab  
+---------------+-----+ 
| descr   | num | 
+---------------+-----+ 
| hello there | 5 | 
| hi there  | 10 | 
| hello   | 10 | 
| hi there!  | 15 | 
+---------------+-----+ 

這個查詢:

SELECT sum(num) AS val FROM tab WHERE descr LIKE "%hello%"; 

應該並且確實返回15。但是:

SELECT sum(num) AS val FROM tab WHERE descr LIKE "%greetings%"; 

應該返回0,但不會返回null

有人可以解釋,如果這是可能的?

回答

44

如何:

SELECT COALESCE(sum(num), 0) AS val FROM tab WHERE descr LIKE "%greetings%"; 

COALESCE功能基本上說「返回的第一個參數,除非它是空在這種情況下返回第二個參數」 - 這是在這些情況下,會非常方便。

+0

這實際上並沒有達到預期效果 - 這也會掩蓋作爲'num'值本身一部分的'NULL'。 – 2017-11-11 04:46:53

+0

它的工作原理,很好的解決方案 – nitin 2017-11-18 07:01:04

1

這工作:

SELECT IF(SUM(num) IS NULL, 0, SUM(num)) AS val FROM tab WHERE descr LIKE "%whatever%"; 

IF()有三個參數:(1)聲明,(2)的值,以適用,如果聲明是真實的,和(3)的值;如果申請聲明是錯誤的。

8

檢查MySQL documentation for IFNULL

SELECT SUM(IFNULL(num, 0)) as val FROM tab WHERE descr LIKE "%greetings%"; 

當然,這裏假設你的num場可爲空並且沒有缺省值。另一個可能的解決方案是爲num字段設置缺省值0,這將解決您遇到的問題。

+6

IFNULL應該在SUM之外,否則如果找不到行,它將返回null。 – 2012-11-30 15:31:41

0

要正確地做到這一點,您可能需要區分在您正在求和的數據中實際存在NULL結果的情況以及根本沒有值求和的情況。

假設我們有以下幾點:

mysql> select * from t; 
+----------+------+ 
| descr | num | 
+----------+------+ 
| hiya  | 5 | 
| hi there | 10 | 
| yo  | NULL | 
+----------+------+ 

我們想空總和爲零,但涉及NULL款項,NULL。一個(而痛苦)的方式做到這一點是:

mysql> SELECT IF(has_null, NULL, total) AS sum FROM (
    -> SELECT COALESCE(MAX(num IS NULL), 0) AS has_null, COALESCE(SUM(num), 0) AS total 
    -> FROM t WHERE num < 'ciao') 
    -> AS u; 
+------+ 
| sum | 
+------+ 
| 0 | 
+------+ 
1 row in set, 1 warning (0.00 sec) 

mysql> SELECT IF(has_null, NULL, total) AS sum FROM (
    -> SELECT COALESCE(MAX(num IS NULL), 0) AS has_null, COALESCE(SUM(num), 0) AS total 
    -> FROM t) 
    -> AS u; 
+------+ 
| sum | 
+------+ 
| NULL | 
+------+ 
1 row in set (0.00 sec) 

mysql> SELECT IF(has_null, NULL, total) AS sum FROM (
    -> SELECT COALESCE(MAX(num IS NULL), 0) AS has_null, COALESCE(SUM(num), 0) AS total 
    -> FROM t WHERE descr < 'namaste') 
    -> AS u; 
+------+ 
| sum | 
+------+ 
| 15 | 
+------+ 
1 row in set (0.00 sec) 

mysql> SELECT IF(has_null, NULL, total) AS sum FROM (
    -> SELECT COALESCE(MAX(num IS NULL), 0) AS has_null, COALESCE(SUM(num), 0) AS total 
    -> FROM t WHERE descr > 'namaste') 
    -> AS u; 
+------+ 
| sum | 
+------+ 
| NULL | 
+------+ 
1 row in set (0.00 sec) 

或許有更好的辦法,我沒有想到的。

不幸的是,SQL標準defines SUM to be null when no elements are summed和MySQL別無選擇,只能遵循該標準。

相關問題