在 MySQL 中 null 不能使用任何运算符与其他字段或者变量(函数、存储过程)进行运算。
创建一个 user 表:
create table user if not exist (id int(10),name varchar(25),constraint id primary key(id));# 插入数据insert into user (id,name) values(1,'李四'),(2, null),(3,''),(4,'王五');
判断 null 的函数:
| 函数 | 含义 |
|---|---|
| isnull(exp) | 判断 exp 是否为 null,如果为 null 函数返回 1,空串和有数据返回 0 |
| ifnull(exp , obj) | 如果 exp 是 null,则用 obj 进行替代 |
测试:
# 查询user表中name不为空的数据,使用name is not null 或 isnull(name) = 0;select * from user where name is not null;select * from user where isnull(name)=0;# 查询user表中name为空的数据,使用 name is null 或 isnull(name)=1;select * from user where name is null;select * from user where isnull(name)=1;# 同时剔除null和空字符串# length():返回字符串的长度# trim():去除字符串左右的空格select * from user where isnull(name)=0 and length(trim(name))>0;# null 的长度为 null# '' 的长度为 0select length(null);select length('');# count()在进行统计某列的记录数的时候,会忽略NULL值,但不会忽略空字符串select count(name) from user; #结果为3
