MySQL: 将 NULL 类型转换为0

让我们假设下表(例如,几个内部 join 语句的结果) :

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

65465 次浏览

Use IFNULL(column, 0) to convert the column value to zero.

Alternatively, the COALESCE function will do the same thing: COALESCE(column, 0), except

  1. COALESCE is ANSI-compliant, IFNULL is not
  2. COALESCE takes an arbitrary number of columns/values and will return the first non-null value passed to it.