平时我们在使用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.”
长度验证:注意空值的''之间是没有空格的。
mysql> select length(''),length(null),length(' ');
+------------+--------------+--------------+
| length('') | length(null) | length(' ') |
+------------+--------------+--------------+
| 0 | NULL | 2 |
+------------+--------------+--------------+
问题2:
判断字段不为空的时候,查询语句到底是用 select * from tablename where columnname <> '' 还是用
select * from tablename where column is not null,2个查询语句有啥不同。
eg:
mysql> show create table testaa;
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| testaa | CREATE TABLE `testaa` (
`a` int(11) NOT NULL,
`b` varchar(20) DEFAULT NULL,
`c` varchar(20) NOT NULL,
PRIMARY KEY (`a`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
mysql> select * from testaa;
+---+------+----+
| a | b | c |
+---+------+----+
| 1 | aa | |
| 2 | | |
| 3 | NULL | |
| 4 | NULL | |
| 5 | aafa | fa |
+---+------+----+
查询验证过程:
mysql> select * from testaa where c is not null;
+---+------+----+
| a | b | c |
+---+------+----+
| 1 | aa | |
| 2 | | |
| 3 | NULL | |
| 4 | NULL | |
| 5 | aafa | fa |
+---+------+----+
5 rows in set (0.00 sec)
mysql> select * from testaa where c <> '';
+---+------+----+
| a | b | c |
+---+------+----+
| 5 | aafa | fa |
+---+------+----+
1 row in set (0.00 sec)
mysql> select * from testaa where c = '';
+---+------+---+
| a | b | c |
+---+------+---+
| 1 | aa | |
| 2 | | |
| 3 | NULL | |
| 4 | NULL | |
+---+------+---+
4 rows in set (0.00 sec)
mysql> select * from testaa where c is null;
Empty set (0.00 sec)
mysql> select * from testaa where b is not null;
+---+------+----+
| a | b | c |
+---+------+----+
| 1 | aa | |
| 2 | | |
| 5 | aafa | fa |
+---+------+----+
3 rows in set (0.00 sec)
mysql> select * from testaa where b <> '';
+---+------+----+
| a | b | c |
+---+------+----+
| 1 | aa | |
| 5 | aafa | fa |
+---+------+----+
2 rows in set (0.00 sec)
mysql> select * from testaa where b ='';
+---+------+---+
| a | b | c |
+---+------+---+
| 2 | | |
+---+------+---+
1 row in set (0.00 sec)
mysql> select * from testaa where b is null;
+---+------+---+
| a | b | c |
+---+------+---+
| 3 | NULL | |
| 4 | NULL | |
+---+------+---+