建表时,列后面的 not null default ‘’/ default 0 就是让这个列值不为 NULL,如果某个列确实没填值,也有默认值,不会为NULL。
为什么不想要NULL的值?
例:
create table test(
name varchar(20)
)engine myisam charset utf8;
insert into values
('lisi'),('wangwu'),('null');
问:这个插入的null,是不是真的null?
答:不是,这只是一个字符串。
insert into test values (NULL);
# 这个才是真的NULL。
# 查询出用户名不为null的行:
select * from teset where name != null;
# 但是返回结果显示 empty set,那么,为什么 lisi 和 wangwu 没查出来呢?
原因:比较时,lisi = null 为假,取不出来;wangwu = null 为假,也取不出来。
原因: null 是空,因此 null 的比较需要用特殊的运算符:is null / is not null
select * from test where name is not null;
# 这次可以取出 lisi 和 wangwu。
回到最初的问题:
为什么不想要null的值?
答:不好比较,null是一种类型,比较时,只能用专门的 is null 和 is not null 来比较,碰到运算符,一律返回 null ;且效率不高,影响提高索引效果。
因此,我们往往在建表时,需要用 not null default ‘’ \0