程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> Oracle數據庫 >> Oracle教程 >> 轉:淺談sql中的in與not in,exists與not exists的區別,sqlexists

轉:淺談sql中的in與not in,exists與not exists的區別,sqlexists

編輯:Oracle教程

轉:淺談sql中的in與not in,exists與not exists的區別,sqlexists


1、in和exists

in是把外表和內表作hash連接,而exists是對外表作loop循環,每次loop循環再對內表進行查詢,一直以來認為exists比in效率高的說法是不准確的。如果查詢的兩個表大小相當,那麼用in和exists差別不大;如果兩個表中一個較小一個較大,則子查詢表大的用exists,子查詢表小的用in;

例如:表A(小表),表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列的索引。

相反的:

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列的索引。

 

2、not in 和not exists

not in 邏輯上不完全等同於not exists,如果你誤用了not in,小心你的程序存在致命的BUG,請看下面的例子:

create table #t1(c1 int,c2 int);create table #t2(c1 int,c2 int);insert into #t1 values(1,2);insert into #t1 values(1,3);insert into #t2 values(1,2);insert into #t2 values(1,null); 

select * from #t1 where c2 not in(select c2 from #t2);  -->執行結果:無select * from #t1 where not exists(select 1 from #t2 where #t2.c2=#t1.c2)  -->執行結果:1  3

正如所看到的,not in出現了不期望的結果集,存在邏輯錯誤。如果看一下上述兩個select 語句的執行計劃,也會不同,後者使用了hash_aj,所以,請盡量不要使用not in(它會調用子查詢),而盡量使用not exists(它會調用關聯子查詢)。如果子查詢中返回的任意一條記錄含有空值,則查詢將不返回任何記錄。如果子查詢字段有非空限制,這時可以使用not in,並且可以通過提示讓它用hasg_aj或merge_aj連接。

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

 

3、in 與 = 的區別

select name from student where name in('zhang','wang','zhao');

select name from student where name='zhang' or name='wang' or name='zhao'

的結果是相同的。

 

原文地址:http://www.cnblogs.com/seasons1987/archive/2013/07/03/3169356.html

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved