mysql 0 null_MySQL:类型为NULL到0

bd96500e110b49cbb3cd949968f18be7.png

Let us suppose the following table (e.g. a result of several inner join statements):

id | column_1 | column_2

------------------------

1 | 1 |

2 | 2 | 2

3 | | 3

Which you could for example get from the following statement:

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

Now, if i'd like to sum up t1.column_1 and t2.column_2 as follows

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

The reslut will look as follows:

id | column_1 | column_2 | cumulated

------------------------------------

1 | 1 | NULL | NULL

2 | 2 | 2 | 4

3 | NULL | 3 | NULL

My question basically is: is there a way to typecast NULL into 0 in order to do some math?

I have tried CONVERT(t1.column_1, SIGNED) and CAST(t1.column_1 as SIGNED), but a NULL stays a NULL.

解决方案

Use IFNULL(column, 0) to convert the column value to zero. Alternatively, the COALESCE function will do the same thing, except (1) COALESCE is ANSI-compliant, IFNULL is not, and (2) COALESCE takes an arbitrary number of columns/values and will return the first non-null value passed to it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值