如何将mysql查询的null结果替换成0?

需求:

在使用mysql执行左联结查询时结果集中有一些字段的值为null,程序没处理空值就会产生异常, 需要在查询时将这部分null值替换为0。


方法:

使用 coalesce函数,它的作用是返回参数中第一个不为null的值,例如:

select coalesce(1,2,3); //返回1

select coalesce(null,2,3); //返回2

select coalesce(null,null,3); //返回3


不过如果参数都是null,那也就只能返回null了。


对于需求我们只需要将第二个参数设置为0就可以了。


测试:

select phrase,ip from log where id = 6;


如何将mysql查询的null结果替换成0?

表中ip的值为空,接着使用COALESCE函数

select phrase,COALESCE(ip,0) from log where id = 6;

如何将mysql查询的null结果替换成0?


分享到:


相關文章: