当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL的空值和NULL区别

MySQL的空值和NULL区别

2019年02月13日  | 移动技术网IT编程  | 我要评论
从本质上区别
1、空值不占空间
2、null值占空间
 
通俗的讲:
空值就像是一个真空转态杯子,什么都没有,而null值就是一个装满空气的杯子,虽然看起来都是一样的,但是有着本质的区别。
 
 
 
例子:
创建一个test表,cola是不可以存放null值的,colb是能存放null值的。
1 create table `test` (
2   `cola` varchar(255) not null,
3   `colb` varchar(255) default null
4 ) engine=innodb default charset=utf8;

 

插入一个null值试试,会发生什么情况?
1 insert into `test`(`cola`, `colb`) values (null, null);

//出现报错,原因是cola是不能插入null值。

 
 
那么如果两个字段同时插入空值,会怎么样。
1 insert into `test`(`cola`, `colb`) values ('', '');

插入成功,说明字段即使设置为null值的时候,是可以插入空值的

 
 
---------------------------------------------------------------查询---------------------------------------------------------
现在表里有三条数据
 
 
接下来我们使用 is not null 和 <> 检索数据表里的数据
1、使用is not null 的查询
1 select * from `test` where cola is not null

 
1 select * from `test` where colb is not null

结论:使用 is not null 查询不会过滤空值,但是会过滤掉null。
 
 
2、使用 <> 的查询
1 select * from `test` where cola <> '';

1 select * from `test` where cola <> '';

结论:使用 <> 会过滤掉null和空值。
 
 
3、使用 count 查询
1 select count(cola) from `test`;

 
1 select count(colb) from `test`;

结论:使用 count 会过滤掉 null 值,但是不会过滤掉空值。
 
 
总结
1、空值不占空间,null值占空间(占用一个字节)。
2、当字段不为null时,也可以插入空值。
3、当使用 is not null 或者 is null 时,只能查出字段中没有不为null的或者为 null 的,不能查出空值。
4、使用 <> 查询时,会筛选掉空值和null值。
5、使用 count 统计时会过滤掉 null 值,但是不会过滤掉空值。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网