平时我们在使用 MySQL 的时候,对于 MySQL 中的 NULL 值和空值区别不能很好的理解。注意到 NULL 值是未知的,且占用空间,不走索引,DBA 建议建表的时候最好设置字段是 NOT NULL 来避免这种低效率的事情的发生。
# 问题 1: 首先,我们需要搞清楚 "空值" 和 "NULL" 的概念
1:空值('')是不占用空间的
2: MySQL中的NULL其实是占用空间的。官方文档说明:
“NULL columns require additional space in the row to record whether their values are NULL. For MyISAM tables, each NULL column takes one bit extra, rounded up to the nearest byte.”
长度验证:注意空值的 '' 之间是没有空格的。
1 | mysql> select length(''),length(null),length(' '); |
# 问题 2:
判断字段不为空的时候,查询语句到底是用 select * from tablename where columnname <> '' 还是用
select * from tablename where column is not null,2 个查询语句有何区别。**
首先创建一张表来看一下区别,下边是新建的测试表中数据
1 | mysql> select * from testaa; |
开始验证:test1
1 | mysql> select * from testaa where c is not null; |
可见使用 is not null 不会过滤掉 '' 空值。
test2
1 | mysql> select * from testaa where c <> ''; |
可见使用 <>'' 可以过滤掉空值;
test3
1 | mysql> select * from testaa where b <> ''; |
可见 <>'' 可以同时过滤掉 null 值和 '' 空值。
test4
看一下 null 和空值是否会计入 count () 行数量
1 | mysql> select count(b),count(c) from testaa; |
可见 NULL 是不会计入数量的,而 '' 空值会计入行数量。
# 总结:
1:在进行 count () 统计某列的记录数的时候,如果采用的 NULL 值,会别系统自动忽略掉,但是空值是会进行统计到其中的。
2: 判断 NULL 用 IS NULL 或者 is not null,SQL 语句函数中可以使用 ifnull () 函数来进行处理,判断空字符用 ='' 或者 <>'' 来进行处理。
By the way 对于 timestamp 数据类型,如果往这个数据类型插入的列插入 NULL 值,则出现的值是当前系统时间。插入空值,则会出现 '0000-00-00 00:00:00' 。
