mysql字段为空(含null、空字符串)的判断

100人浏览   2025-01-20 00:00:19

项目中经常遇到判断 varchar 类型字段是否为空,包含空字符串('') 和null ,对其处理不当就会坑你一把,弄的你一点脾气都没有,应小伙伴儿们要求,这里写篇手记,对空字段的处理做下说明。
数据库,新建表 a 结构、数据:

表结构

表数据

-- 1.执行结果是什么?

select * from a where length(name)=0;

查询结果

-- 2.执行结果是什么?

select * from a where name is null ;

查询结果

看到这,是不是明白点了,null比较特殊,使用函数对其操作,只会返回null

由此得出结论:
select length(null) ; ==> null
select length(’’); ==> 0

常见写法:

where column1 is null or length(column1)=0;

或者

where ifnull(column1,'')='';

这两种写法有问题,where条件中使用函数当条件会导致索引失效!

性能最好的写法就是 column1 is null or column1 =''

相关推荐