文章中所有操作均是在 MySQL 5.7 版本下进行的
区分空字符串和NULL
数据库存储数据有必要搞清空值,空字符串和 NULL 的概念。
- 空字符串是单引号引的,它其实是不占空间的。
- MySQL 中 null 其实是占空间的,官网文档里有说明。
它们之前的长度验证:
select length('') as '空串', length(null) as 'null', length(' ') as '空格字符串';
+--------+------+-----------------+
| 空串 | null | 空格字符串 |
+--------+------+-----------------+
| 0 | NULL | 1 |
+--------+------+-----------------+
如何查询空字符串和NULL
-- 创建测试表
drop table if exists tbl_test;
create table tbl_test(
id int primary key,
info varchar(50)
);
-- 插入测试数据
insert into tbl_test (id, info) values (1, null);
insert into tbl_test (id, info) values (2, '');
insert into tbl_test (id, info) values (3, 'null');
insert into tbl_test (id, info) values (4, ' '); -- 带空格的字符串
查询null的数据
select * from tbl_test where info is null;
+----+------+
| id | info |
+----+------+
| 1 | NULL |
+----+------+
/*
不是null的就是 is not null
id=3的数据那是一个null的字符串,不等同与null
*/
查询空串的数据
select * from tbl_test where info = '';
+----+------+
| id | info |
+----+------+
| 2 | |
| 4 | |
+----+------+
-- 以上把id=4的空串也给查询出来了,其实id=4并不是我想要的,处理如下
select * from tbl_test where info = binary'';
+----+------+
| id | info |
+----+------+
| 2 | |
+----+------+
能不能给唯一约束的字段插入NULL或者空串
-- 先清空了数据
delete from tbl_test;
-- 修改变增加一个字段并增加唯一约束
alter table tbl_test add num int;
alter table tbl_test add unique(num);
加入空串数据
insert into tbl_test (id, num) values (1, '');
-- 试过知道,以上语句报错,是因为不能将空串加入到唯一约束的字段中
加入null数据
insert into tbl_test (id, num) values (2, null);
insert into tbl_test (id, num) values (3, null);
-- 以上语句没有问题,所以可以给唯一约束的字段增加null数据,而且可以是多个
结语
null 其实并不是空值,而是要占用空间,所以 MySQL 在进行比较的时候,null 会参与字段比较,所以对效率有一部分影响。对于表索引时不会存储 null 值的,所以如果索引的字段可以为 null,索引的效率会下降很多。
空值也不一定为空,对于 timestamp 数据类型,如果往这个数据类型插入的列插入 null 值,则出现的值是当前系统时间。插入空值,则会出现 ‘0000-00-00 00:00:00’。