MySQL字段允许为空之后

建表语句

create table user (id int, name varchar(20), index(id))engine=innodb;

insert into user values(1,'阳光女孩');

建表时请手动添加一行id为null 的数据

1.负向查询索引不能命中,导致全表扫描

explain select * from user where id != 2; 

type:all  

2. 不等于(!=)不等同于 is null

select * from user where id != 2;  不会查询去id为null 的数据

3.此时使用关键字or也会导致全表扫描,建议使用union进行优化

select * from user where id is null 走索引

select * from user where id = 1 走索引

select * from user where id = 1 or id is null 不走索引

这时建议使用union优化:

select * from user where id = 1 union select * from user where id = 1 or id is null 走索引

你可能感兴趣的:(MySQL字段允许为空之后)