Answers:
使用COALESCE
以避免这种结果。
SELECT COALESCE(SUM(column),0)
FROM table
WHERE ...
要查看它的实际效果,请参阅以下sql小提琴:http ://www.sqlfiddle.com/#!2/d1542/3 /0
更多信息:
给定三张表(一张带有所有数字,一张带有所有空值,一张带有混合数):
MySQL 5.5.32模式设置:
CREATE TABLE foo
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO foo (val) VALUES
(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);
CREATE TABLE bar
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO bar (val) VALUES
(1),(2),(3),(4),(5),(6);
CREATE TABLE baz
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO baz (val) VALUES
(null),(null),(null),(null),(null),(null);
查询1:
SELECT 'foo' as table_name,
'mixed null/non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM foo
UNION ALL
SELECT 'bar' as table_name,
'all non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM bar
UNION ALL
SELECT 'baz' as table_name,
'all null' as description,
0 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM baz
结果:
| TABLE_NAME | DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |
|------------|---------------------|--------------|------------|
| foo | mixed null/non-null | 21 | 21 |
| bar | all non-null | 21 | 21 |
| baz | all null | 0 | 0 |
SELECT IFNULL(SUM(Column1), 0) AS total FROM...
SELECT COALESCE(SUM(Column1), 0) AS total FROM...
它们之间的区别在于,它IFNULL
是一个带有两个参数的MySQL扩展,并且COALESCE
是一个可以带有一个或多个参数的标准SQL函数。当您只有两个参数时,使用IFNULL
会稍微快一些,尽管此处的区别不明显,因为仅被调用一次。
IFNULL
或COALESCE
?? 你能解释一下吗?
coalesce
。
无法确切地得到您所要的信息,但是如果您使用的是汇总SUM函数,这意味着您正在对表进行分组。
查询是这样的MYSQL
Select IFNULL(SUM(COLUMN1),0) as total from mytable group by condition