exists和in, not exists和not in
阿新 • • 發佈:2018-12-13
【1】exists
對外表用loop逐條查詢,每次查詢都會檢視exists的條件語句。
當 exists裡的條件語句能夠返回記錄行時(無論記錄行是多少,只要能返回),條件就為真 , 返回當前loop到的這條記錄。反之如果exists裡的條件語句不能返回記錄行,條件為假,則當前loop到的這條記錄被丟棄。
exists的條件就像一個boolean條件,當能返回結果集則為1,不能返回結果集則為 0。
語法格式如下:
select * from tables_name where [not] exists(select..);
示例如下:
select * from p_user_2 where EXISTS(select * from p_user where id=12)
如果p_user表中有id為12的記錄,那麼將返回所有p_user_2表中的記錄;否則,返回記錄為空。
如果是not exists,則與上述相反。
總的來說,如果A表有n條記錄,那麼exists查詢就是將這n條記錄逐條取出,然後判斷n遍exists條件
【2】in
語法格式如下:
select * from A where column in (select column from B);
需要說明的是,where中,column為A的某一列,in 所對應的子查詢語句返回為一列多行結果集。
注意,in所對應的select語句返回的結果一定是一列!可以為多行。
示例如下:
select * from p_user_2 where id [not] in (select id from p_user )
查詢id在p_user表id集合的p_user_2的記錄。not in則相反。
【3】exists與in的關係
經過sql改變,二者是可以達到同一個目標的:
select * from p_user_2
where id [not] in (select id from p_user );
select * from p_user_2
where [not] EXISTS (select id from p_user where id = p_user_2.id )
那麼什麼時候用exists 或者in呢?
如果查詢的兩個表大小相當,那麼用in和exists差別不大。
如果兩個表中一個較小,一個是大表,則子查詢表大的用exists,子查詢表小的用in :
例如:表A(小表),表B(大表)
① 子查詢表為表B:
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列的索引。
② 子查詢表為表A:
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要快。