mysql null diff - yaokun123/php-wiki GitHub Wiki
Mysql空值和NULL区别
一、占用空间区别
mysql> select length(NULL), length(''), length('1');
+--------------+------------+-------------+
| length(NULL) | length('') | length('1') |
+--------------+------------+-------------+
| NULL | 0 | 1 |
+--------------+------------+-------------+
从上面看出空值('')的长度是0,是不占用空间的;而的NULL长度是NULL,其实它是占用空间的,看下面说明。 NULL columns require additional space in the row to record whether their values are NULL. NULL列需要行中的额外空间来记录它们的值是否为NULL。
通俗的讲:空值就像是一个真空转态杯子,什么都没有,而NULL值就是一个装满空气的杯子,虽然看起来都是一样的,但是有着本质的区别。
二、插入/查询方式区别
创建一个表,tb_test
CREATE TABLE `tb_test` (
`one` varchar(10) NOT NULL,
`two` varchar(255) DEFAULT NULL )
ENGINE=InnoDB DEFAULT CHARSET=utf8;
插入进行验证:
//-- 全部插入 NULL,失败
mysql> INSERT tb_test VALUES (NULL,NULL); 1048 - Column 'one' cannot be null
//-- 全部插入 空值,成功
mysql> INSERT tb_test VALUES ('',''); Query OK, 1 row affected
查询验证:
模拟数据:
INSERT tb_test VALUES (1,NULL);
INSERT tb_test VALUES ('',2);
INSERT tb_test VALUES (3,3);
-- 使用 is null/is not null
mysql> SELECT * FROM tb_test where one is NULL;//Empty
mysql> SELECT * FROM tb_test where two is NULL;//1 row in set
mysql> SELECT * FROM tb_test where one is not NULL;//3 rows in set
mysql> SELECT * FROM tb_test where two is not NULL;//2 rows in set
-- 使用 = 、!=
mysql> SELECT * FROM tb_test where one = '';//1 row in set
mysql> SELECT * FROM tb_test where two = '';//Empty set
mysql> SELECT * FROM tb_test where one != '';//2 rows in set
mysql> SELECT * FROM tb_test where two != '';//2 rows in set
小总结:如果要单纯查NULL值列,则使用 is NULL去查,单纯去查空值('')列,则使用 =''。 建议查询方式:NULL值查询使用is null/is not null查询,而空值('')可以使用=或者!=、<、>等算术运算符。
三、COUNT函数
使用COUNT函数:
mysql> SELECT count(one) FROM tb_test;//3
mysql> SELECT count(two) FROM tb_test;//2
mysql> SELECT count(*) FROM tb_test;//3
小总结:使用 COUNT(字段) 统计会过滤掉 NULL 值,但是不会过滤掉空值。