Mysql字段判空实用技巧

文章目录

背景

在日常SQL处理中,如何对字段的空值进行处理,记录下来,方便备查。

函数判空

MySQL中可使用【ifnull】函数,该函数对空值可以判断,即数据库中值为【null】

ifnull(str,replaceStr)

str : 需要判空的字符串

replaceStr :若是为空,将要替换的值

素材

金额计算的业务场景中,若金额为空,则默认赋值为0

方案一、case函数

使用case when 捕获空串情况,进行赋值处理。

java 复制代码
select case when ifnull(amount,'') = '' then '0' end as totalAmount from dual

验证SQL

java 复制代码
select '' as k, case when ifnull('','') = '' then '0' end as totalAmount from dual
union
select null as k, case when ifnull(null,'') = '' then '0' end as totalAmount from dual

实现效果如下所示。

方案二、nullif函数

可使用【nullif】函数,捕获空串情况

java 复制代码
select ifnull(nullif(amount,''),'0') as totalAmount from dual

nullif(str1,str2)

若两个值相等,则返回null

相关推荐
酸菜牛肉汤面3 小时前
23、varchar与char的区别
数据库
To Be Clean Coder3 小时前
【Spring源码】getBean源码实战(三)
java·mysql·spring
AI题库4 小时前
PostgreSQL 18 从新手到大师:实战指南 - 2.5 Serverless PostgreSQL
数据库·postgresql·serverless
IT技术分享社区4 小时前
数据库实战:MySQL多表更新JOIN操作的底层原理与性能调优指南
数据库·mysql·程序员
廋到被风吹走4 小时前
【数据库】【Oracle】分区表与大表设计
数据库·oracle
龘龍龙4 小时前
Python基础(九)
android·开发语言·python
UrSpecial4 小时前
InnoDB存储引擎
数据库·mysql
gjc5925 小时前
MySQL隐蔽 BUG:组合条件查询无故返回空集?深度排查与规避方案
android·数据库·mysql·bug
❀͜͡傀儡师5 小时前
docker部署PostgreSQL数据库的监控和管理工具
数据库·docker·postgresql