MySQL:将NULL转换为0

88

假设有以下表格(例如,多个内连接语句的结果):

id | column_1 | column_2
------------------------
 1 |  1       | 
 2 |  2       | 2
 3 |          | 3

你可以从以下语句中获取例如:

select a.id, t1.column_1, t2.column_2
from a
left join t1 on a.id = t1.id
left join t2 on a.id = t2.id

现在,如果我想把t1.column_1和t2.column_2相加如下

select 
    a.id, 
    t1.column_1, 
    t2.column_2,
    (t1.column_1 + t2.column_2) as cumulated
from a
left join t1 on a.id = t1.id
left join t2 on a.id = t2.id
结果将如下所示:
id | column_1 | column_2 | cumulated
------------------------------------
 1 |  1       | NULL     | NULL
 2 |  2       | 2        | 4
 3 |  NULL    | 3        | NULL
 

我的问题基本上是:有没有一种方法可以将NULL强制转换为0,以进行数学运算?

我已经尝试过CONVERT(t1.column_1, SIGNED)CAST(t1.column_1 as SIGNED),但是NULL仍然是NULL

1个回答

164

使用IFNULL(column,0)将列值转换为零。

或者,COALESCE函数也可以做同样的事情:COALESCE(column,0),除了

  1. COALESCE是符合ANSI标准的,而IFNULL不符合标准。
  2. COALESCE可以接受任意数量的列/值,并返回传递给它的第一个非空值。

and coalesce 可以有多个值吗? - ante.sabo
10
是的,COALESCE(column1, column2, 0)会返回这些值中第一个非空的值。请注意,此操作是按行执行的而不是按列执行的,这些列必须属于同一行的表格。 - David Andres
@rexem:谢谢,你说的太好了。非常感激! - David Andres
@David Andres 无尽感谢。如果我能再次点赞就好了。 - story

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接