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 走索引

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容