1. 程式人生 > >MySql中exists和in的區別

MySql中exists和in的區別

exists介紹

exists對外表用loop逐條查詢,每次查詢都會檢視exists的條件語句,當 exists裡的條件語句能夠返回記錄行時(無論記錄行是的多少,只要能返回),條件就為真,返回當前loop到的這條記錄,反之如果exists裡的條 件語句不能返回記錄行,則當前loop到的這條記錄被丟棄,exists的條件就像一個bool條件,當能返回結果集則為true,不能返回結果集則為 false
如下:
select * from user where exists (select 1);
對user表的記錄逐條取出,由於子條件中的select 1永遠能返回記錄行,那麼user表的所有記錄都將被加入結果集,所以與 select * from user;是一樣的
又如下:
select * from user where exists (select * from user where userId = 0);
可以知道對user表進行loop時,檢查條件語句(select * from user where userId = 0),由於userId永遠不為0,所以條件語句永遠返回空集,條件永遠為false,那麼user表的所有記錄都將被丟棄
not exists與exists相反,也就是當exists條件有結果集返回時,loop到的記錄將被丟棄,否則將loop到的記錄加入結果集
總的來說,如果A表有n條記錄,那麼exists查詢就是將這n條記錄逐條取出,然後判斷n遍exists條件 
 

in介紹

in查詢相當於多個or條件的疊加,這個比較好理解,比如下面的查詢
select * from user where userId in (1, 2, 3);
等效於
select * from user where userId = 1 or userId = 2 or userId = 3;
總的來說,in查詢就是先將子查詢條件的記錄全都查出來,假設結果集為B,共有m條記錄,然後在將子查詢條件的結果集分解成m個,再進行m次查詢

 

注意

in查詢的子條件返回結果必須只有一個欄位,例如
select * from user where userId in (select id from B);
而不能是
select * from user where userId in (select id, age from B);
而exists就沒有這個限制

 

查詢效率

一直大家都認為exists比in語句的效率要高,這種說法其實是不準確的。這個是要區分環境的
如果查詢的兩個表大小相當,那麼用in和exists差別不大。 
如果兩個表中一個較小,一個是大表,則子查詢表大的用exists,子查詢表小的用in: 
例如:表A(小表),表B(大表)
1:
select * from A where cc in (select cc from B) 效率低,用到了A表上cc列的索引;
select * from A where exists(select cc from B where cc=A.cc) 效率高,用到了B表上cc列的索引。 
2:
select * from B where cc in (select cc from A) 效率高,用到了B表上cc列的索引;
select * from B where exists(select cc from A where cc=B.cc) 效率低,用到了A表上cc列的索引。
 

同時not in 和not exists,如果查詢語句使用了not in 那麼內外表都進行全表掃描,沒有用到索引,而not extsts 的子查詢依然能用到表上的索引。所以無論那個表大,用not exists都比not in要快。 

 

轉自http://sunxiaqw.blog.163.com/blog/static/990654382013430105130443/