为什么 COALESCE() 不起作用?

sta*_*ack 3 mysql sum

这是我的查询:

select COALESCE(t1.col1, 0) from table1 t1 where table2.id = t1.col2
Run Code Online (Sandbox Code Playgroud)

因此,输出有时为。为什么?我使用的COALESCE()只是因为如果结果为空,则0改为放置。我该如何解决?

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

select COALESCE(sum(t1.col1), 0) from table1 t1 where table2.id = t1.col2
Run Code Online (Sandbox Code Playgroud)

编辑:其实我想说:如果没有结果(没有建立行)返回0

Gor*_*off 7

如果这是您的查询:

select COALESCE(t1.col1, 0)
from table1 t1
where id = 10;
Run Code Online (Sandbox Code Playgroud)

那么当没有匹配时它不会返回任何行。如果你知道你想要一行,你可以使用聚合:

select COALESCE(MAX(t1.col1), 0)
from table1 t1
where id = 10;
Run Code Online (Sandbox Code Playgroud)

这保证返回一行,它不会是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);
Run Code Online (Sandbox Code Playgroud)

或者,另一种方式:

select coalesce((select col1 from table1 where id = 10),
                0)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,行的缺失变成了一个标NULL量值,所以COALESCE()可以解决这个问题。

请注意: COALESCE()工作正常。您需要意识到它适用于列值。当没有返回时,它不能召唤一行。