數據庫in/exists用法和效率大揭密

之前沒注意到這兩者的差別。

其實,這裏還是有一定的陷阱的。

先看下代碼:

  1. select count(*) from (  
  2. ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc )  
  3.  union  
  4.   ( select stu.XH as xh   
  5.      from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc  
  6.     where  cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1  
  7.     and (stu.xh not exists (select sc.xh from "JISUANJI"."STUDENTCHECK" sc))  
  8.     )  
  9.   ) t1    
(運行錯誤,會報無效的關係運算符)

不細心地認爲這是沒有問題的,但是,它確實存在着差別。

  1. select count(*) from (  
  2. ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc )  
  3.  union  
  4.   ( select stu.XH as xh   
  5.      from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc  
  6.     where  cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1  
  7.     and (stu.xh not in (select sc.xh from "JISUANJI"."STUDENTCHECK" sc))  
  8.     )  
  9.   ) t1    

運行正確

運行出錯的代碼應該改爲:

  1. select count(*) from (  
  2. ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc )  
  3.  union  
  4.   ( select stu.XH as xh   
  5.      from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc  
  6.     where  cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1  
  7.     and ( not exists (select sc.xh from "JISUANJI"."STUDENTCHECK" sc))  
  8.     )  
  9.   ) t1    


1.使用方式上的差別。

where stu.xh not in

where ont exits 

exists是不需要加上字段名字的。


有時候你會發現,運行好像沒問題。

但是,它還是存在的問題的!數值也行有時候是正確的。這可能誤導的!


  1. select count(*) from (  
  2. ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc )  
  3.  union  
  4.   ( select stu.XH as xh   
  5.      from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc  
  6.     where  cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1  
  7.     and ( <span style="color:#ff0000;">not exists (select sc.xh from "JISUANJI"."STUDENTCHECK" sc where stu.xh= sc.xh</span>))  
  8.     )  
  9.   ) t1    
這纔是最終的exists的使用方法。

exists關鍵字使用的時候,需要關聯的!

爲什麼呢?

這個就是in/exists之間的原理的差別了

很多時候,有人跟你說,都使用exists,exists比in效率高!

但是,這個不是正確的了。可以說,exists使用比較多!

結論是:

<strong style="background-color:rgb(255,255,255)"><span style="color:#ff0000;">如果兩個表中一個較小,一個是大表,則子查詢表大的用exists,子查詢表小的用in</span></strong>
<span style="background-color:rgb(255,255,255)"><span style="color:#ff0000;">如果兩個表都差不多一樣大的話,效率是差不多的!</span></span>
這是因爲,
in 是把外表和內表作hash join,而exists是對外表作loop,每次loop再對內表進行查詢。每次循環查的時候,和in模式不一樣的地方是:返回值是真或假,是真就輸出。
發佈了189 篇原創文章 · 獲贊 80 · 訪問量 41萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章