數據庫允許空值(null)出現的問題

原文鏈接:https://mp.weixin.qq.com/s?__biz=MjM5ODYxMDA5OQ==&mid=2651962495&idx=1&sn=74e9e0dc9d03a872fd5bce5769f6c22a&chksm=bd2d09a38a5a80b50da3b67c03da8417426cbb201427557959fa91e9094a848a14e0db214370&scene=21#wechat_redirect

數據庫允許空值(null)出現的問題

數據準備:

create table user (

id int,

name varchar(20),

index(id)

)engine=innodb;

insert into user values(1,'shenjian');

insert into user values(2,'zhangsan');

insert into user values(3,'lisi');

說明:
id爲索引,非唯一(non unique),允許空(null)。

知識點1(熱身):負向查詢不能命中索引,會導致全表掃描。
在這裏插入圖片描述

explain select * from user where id!=1;

索引字段id上的不等於查詢,如上圖所示:

(1)type=ALL,全表掃描;

(2)rows=3,全表只有3行;

知識點2(劃重點):允許空值,不等於(!=)查詢,可能導致不符合預期的結果。
在這裏插入圖片描述

insert into user(name) values('wangwu');

先構造一條id爲NULL的數據,可以看到共有4條記錄。

select * from user where id!=1;

再次執行不等於查詢。

結果集只有2條記錄,空值記錄記錄並未出現在結果集裏。
在這裏插入圖片描述

select * from user where id!=1 or id is null;

如果想到得到符合預期的結果集,必須加上一個or條件。

知識點3(附加):某些or條件,又可能導致全表掃描,此時應該優化爲union。
在這裏插入圖片描述

explain select * from user where id=1;

索引字段id上的等值查詢,能命中索引,如上圖所示:

(1)type=ref,走非唯一索引;

(2)rows=1,預估掃描1行;
在這裏插入圖片描述
explain select * from user where id is null;

索引字段id上的null查詢,也能命中索引,如上圖所示:

(1)type=ref,走非唯一索引;

(2)rows=1,預估掃描1行;
在這裏插入圖片描述

explain select * from user where id=1 or id is null;

如果放到一個SQL語句裏用or查詢,則會全表掃描,如上圖所示:

(1)type=ALL,全表掃描;

(2)rows=4,全表只有4行;
在這裏插入圖片描述

explain select * from user where id=1 

union

select * from user where id is null;

此時應該優化爲union查詢,又能夠命中索引了,如上圖所示:

(1)type=ref,走非唯一索引;

(2)rows=1,預估掃描1行;

第三行臨時表的ALL,是兩次結果集的合併。

總結

(1)負向比較(例如:!=)會引發全表掃描;

(2)如果允許空值,不等於(!=)的查詢,不會將空值行(row)包含進來,此時的結果集往往是不符合預期的,此時往往要加上一個or條件,把空值(is null)結果包含進來;

(3)or可能會導致全表掃描,此時可以優化爲union查詢;

(4)建表時加上默認(default)值,這樣能避免空值的坑;

(5)explain工具是一個好東西;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章