MySQL: Typecasting NULL to 0(MySQL:将 NULL 类型转换为 0)
问题描述
让我们假设下表(例如几个内部连接语句的结果):
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
现在,如果我想总结 t1.column_1 和 t2.column_2 如下
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
结果如下:
id | column_1 | column_2 | cumulated
------------------------------------
1 | 1 | NULL | NULL
2 | 2 | 2 | 4
3 | NULL | 3 | NULL
我的问题基本上是:有没有办法将 NULL 类型转换为 0 以进行一些数学运算?
My question basically is: is there a way to typecast NULL into 0 in order to do some math?
我尝试过 CONVERT(t1.column_1, SIGNED) 和 CAST(t1.column_1 as SIGNED),但是 NULL 仍然是NULL.
I have tried CONVERT(t1.column_1, SIGNED) and CAST(t1.column_1 as SIGNED), but a NULL stays a NULL.
推荐答案
使用 IFNULL(column, 0) 将列值转换为零.
Use IFNULL(column, 0) to convert the column value to zero.
或者,COALESCE 函数会做同样的事情:COALESCE(column, 0),除了
Alternatively, the COALESCE function will do the same thing: COALESCE(column, 0), except
COALESCE符合 ANSI,IFNULL不是COALESCE接受任意数量的列/值,并将返回传递给它的第一个非空值.
COALESCEis ANSI-compliant,IFNULLis notCOALESCEtakes an arbitrary number of columns/values and will return the first non-null value passed to it.
这篇关于MySQL:将 NULL 类型转换为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL:将 NULL 类型转换为 0
基础教程推荐
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 无法解决整理冲突 2021-01-01
