這兩個(gè)小技巧,讓SQL語(yǔ)句不僅躲了坑,還提升了1000倍
本次來(lái)講解與 SQL 查詢有關(guān)的兩個(gè)小知識(shí)點(diǎn),掌握這些知識(shí)點(diǎn),能夠讓你避免踩坑以及提高查詢效率。
1、允許字段的值為 null,往往會(huì)引發(fā)災(zāi)難
首先,先準(zhǔn)備點(diǎn)數(shù)據(jù),后面好演示
- create table animal(
- id int,
- name char(20),
- index(id)
- )engine=innodb;
index(id) 表示給 id 這個(gè)字段創(chuàng)建索引,并且 id 和 name 都允許為 null。
接著插入4條數(shù)據(jù),其中最后一條數(shù)據(jù)的 id 為。
- insert into animal(id, name) values(1, '貓');
- insert into animal(id, name) values(2, '狗');
- insert into animal(id, name) values(3, '豬');
- insert into animal(id, name) values(null, '無(wú)名動(dòng)物');
(注意:代碼塊可以左右拉動(dòng))
此時(shí)表中的數(shù)據(jù)為
這時(shí)我們查詢表中 id != 1 的動(dòng)物有哪些
- select * from animal where id != 1;
結(jié)果如下:
此時(shí)我們只找到了兩行數(shù)據(jù),按道理應(yīng)該是三行的,但是 id = null 的這一行居然沒(méi)有被匹配到,,可能大家聽(tīng)說(shuō)過(guò),null 與任何
其他值都不相等,按道理 null != 1 是成立的話,然而現(xiàn)實(shí)很殘酷,它就是不會(huì)被匹配到。
所以,堅(jiān)決不允許字段的值為 null,否則可能會(huì)出現(xiàn)與預(yù)期不符合的結(jié)果。
反正我之前有踩過(guò)這個(gè)坑,不知道大家踩過(guò)木有?
但是萬(wàn)一有人設(shè)置了允許為 null 值怎么辦?如果真的這樣的話,對(duì)于 != 的查找,后面可以多加一個(gè) or id is null 的子句(注意,是 is null,不是 = null,因?yàn)?id = null 也不會(huì)匹配到值為 null 的行)。即
- select * from animal where id != 1 or id is null;
結(jié)果如下:
2、盡可能用 union 來(lái)代替 or
(1)、剛才我們給 id 這個(gè)字段建立了索引,如果我們來(lái)進(jìn)行等值操作的話,一般會(huì)走索引操作,不信你看:
- explain select * from animal where id = 1;
結(jié)果如下:
通過(guò)執(zhí)行計(jì)劃可以看見(jiàn),id 上的等值查找能夠走索引查詢(估計(jì)在你的意料之中),其中
type = ref :表示走非唯一索引
rows = 1 :預(yù)測(cè)掃描一行
(2)、那 id is null 會(huì)走索引嗎?答是會(huì)的,如圖
- explain select * from animal where id is null;
其中
type = ref :表示走非唯一索引
rows = 1 :預(yù)測(cè)掃描一行
(3)、那么問(wèn)題來(lái)了,那如果我們要找出 id = 1 或者 id = null 的動(dòng)物,我們可能會(huì)用 or 語(yǔ)句來(lái)連接,即
- select * from animal where id = 1 or id is null;
那么這條語(yǔ)句會(huì)走索引嗎?
有沒(méi)有走索引,看執(zhí)行計(jì)劃就知道了,如圖
- explain select * from animal where id = 1 or id is null;
其中:
ref = ALL:表示全表掃描
rows = 4 :預(yù)測(cè)掃描4行(而我們整個(gè)表就只有4行記錄)
通過(guò)執(zhí)行計(jì)劃可以看出,使用 or 是很有可能不走索引的,這將會(huì)大大降低查詢的速率,所以一般不建議使用 or 子句來(lái)連接條件。
那么該如何解決?
其實(shí)可以用 union 來(lái)取代 or,即如下:
- select * from animal where id = 1 union select * from animal where id is null.
此時(shí)就會(huì)分別走兩次索引,找出所有 id = 1 和 所有 id = null 的行,然后再用一個(gè)臨時(shí)表來(lái)存放最終的結(jié)果,最后再掃描臨時(shí)表。
3、總結(jié)
1、定義表的時(shí)候,盡量不允許字段值為 null,可以用 default 設(shè)置默認(rèn)值。
2、盡量用 union 來(lái)代替 or,避免查詢沒(méi)有走索引。
3、注意,用 id = null 的等值查詢,也是不會(huì)匹配到值為 null 的行的,而是應(yīng)該用 id is null。
也歡迎大家說(shuō)一說(shuō)自己踩過(guò)的坑。




































