Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 为什么COALESCE()不起作用?_Mysql_Sum - Fatal编程技术网

Mysql 为什么COALESCE()不起作用?

Mysql 为什么COALESCE()不起作用?,mysql,sum,Mysql,Sum,我的问题是: select COALESCE(t1.col1, 0) from table1 t1 where table2.id = t1.col2 因此,输出有时是空的。为什么?我使用了COALESCE(),只是因为如果结果为空,它会将0替换为空。我怎样才能修好它 注意:COALESCE()也适用于此查询: select COALESCE(sum(t1.col1), 0) from table1 t1 where table2.id = t1.col2 编辑:实际上我想说:如果没有结果

我的问题是:

select COALESCE(t1.col1, 0) from table1 t1 where table2.id = t1.col2
因此,输出有时是空的。为什么?我使用了
COALESCE()
,只是因为如果结果为空,它会将
0
替换为空。我怎样才能修好它

注意:
COALESCE()
也适用于此查询:

select COALESCE(sum(t1.col1), 0) from table1 t1 where table2.id = t1.col2

编辑:实际上我想说:如果没有结果(没有找到行),则返回
0

如果这是您的查询:

select COALESCE(t1.col1, 0)
from table1 t1
where id = 10;
当没有匹配项时,它将不会返回任何行。如果您知道需要一行,可以使用聚合:

select COALESCE(MAX(t1.col1), 0)
from table1 t1
where id = 10;
这保证返回一行,并且不会为
NULL
。另一种方法使用
union all

select t1.col1
from table1 t1
where id = 10
union all
select 0
from table1 t1
where not exists (select 1 from table1 where id = 10);
或者,另一种方式:

select coalesce((select col1 from table1 where id = 10),
                0)
在此上下文中,缺少行被转换为标量
NULL
值,因此
COALESCE()
可以处理该问题


请注意:
COALESCE()
工作正常。您需要意识到它对列值有效。当未返回任何行时,它无法召唤行。

我也尝试了
IFNULL(t1.col1,0)
但也不起作用。coalesce返回第一个非空值,而不是第一个非空值。此外,where子句中提到了表2,但表列表中没有提到。我希望这会给出一个错误。您确定t1.col1为NULL,而不仅仅是一个空(零长度)字符串吗。它们不一样,只使用COALESCE/ISNULL函数,正如您对前者所期望的那样。尝试使用CASE WHEN t1.col1=“”然后使用0 ELSE t1.col1 end此处没有表2。完美。。。!这个答案正是我想要的+1.