为什么COALESCE()不起作用?

时间:2015-11-21 22:56:23

标签: 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

修改:其实我想说:如果没有结果(没有创建行)返回0

1 个答案:

答案 0 :(得分:4)

如果这是您的查询:

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()工作正常。您需要意识到它适用于列值。当没有人返回时,它不会召唤出一行。