在 MySQL 中 null 不能使用任何运算符与其他字段或者变量(函数、存储过程)进行运算。

    创建一个 user 表:

    1. create table user if not exist (
    2. id int(10),
    3. name varchar(25),
    4. constraint id primary key(id)
    5. );
    6. # 插入数据
    7. insert into user (id,name) values
    8. (1,'李四'),
    9. (2, null),
    10. (3,''),
    11. (4,'王五');

    判断 null 的函数:

    函数 含义
    isnull(exp) 判断 exp 是否为 null,如果为 null 函数返回 1,空串和有数据返回 0
    ifnull(exp , obj) 如果 exp 是 null,则用 obj 进行替代

    测试:

    1. # 查询user表中name不为空的数据,使用name is not null 或 isnull(name) = 0;
    2. select * from user where name is not null;
    3. select * from user where isnull(name)=0;
    4. # 查询user表中name为空的数据,使用 name is null 或 isnull(name)=1;
    5. select * from user where name is null;
    6. select * from user where isnull(name)=1;
    7. # 同时剔除null和空字符串
    8. # length():返回字符串的长度
    9. # trim():去除字符串左右的空格
    10. select * from user where isnull(name)=0 and length(trim(name))>0;
    11. # null 的长度为 null
    12. # '' 的长度为 0
    13. select length(null);
    14. select length('');
    15. # count()在进行统计某列的记录数的时候,会忽略NULL值,但不会忽略空字符串
    16. select count(name) from user; #结果为3