1、in 與 exists:
外表大,用IN;內表大,用EXISTS;
原理:
用in:外表使用了索引,直接作hash連接;
用exists:內表使用了索引,外表作loop循環再進行匹配;
2、not in與not exists:
性能:not in不走索引,所以一般都用not exists;
區別:還有一點區別就是,not in字段爲null的不進行篩選出來;而使用not exists即可;
這也就是說有時定義字段,用not null比較好了,這樣也能避免not in查詢出錯。
exists : 強調的是是否返回結果集,不要求知道返回什麼, 比如:
select name from student where sex = 'm' and mark exists(select 1 from grade where ...) ,只要
exists引導的子句有結果集返回,那麼exists這個條件就算成立了,大家注意返回的字段始終爲1,如果改成“select 2 from grade where ...”,那麼返回的字段就是2,這個數字沒有意義。所以exists子句不在乎返回什麼,而是在乎是不是有結果集返回。
而 exists 與 in 最大的區別在於 in引導的子句只能返回一個字段,比如:
select name from student where sex = 'm' and mark in (select 1,2,3 from grade where ...)
,in子句返回了三個字段,這是不正確的,exists子句是允許的,但in只允許有一個字段返回,在1,2,3中隨便去了兩個字段即可。
而not exists 和not in 分別是exists 和 in 的 對立面。
exists (sql 返回結果集爲真)
not exists (sql 不返回結果集爲真)