之前沒注意到這兩者的差別。
其實,這裏還是有一定的陷阱的。
先看下代碼:
- select count(*) from (
- ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc )
- union
- ( select stu.XH as xh
- from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc
- where cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1
- and (stu.xh not exists (select sc.xh from "JISUANJI"."STUDENTCHECK" sc))
- )
- ) t1
不細心地認爲這是沒有問題的,但是,它確實存在着差別。
- select count(*) from (
- ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc )
- union
- ( select stu.XH as xh
- from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc
- where cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1
- and (stu.xh not in (select sc.xh from "JISUANJI"."STUDENTCHECK" sc))
- )
- ) t1
運行正確
運行出錯的代碼應該改爲:
- select count(*) from (
- ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc )
- union
- ( select stu.XH as xh
- from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc
- where cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1
- and ( not exists (select sc.xh from "JISUANJI"."STUDENTCHECK" sc))
- )
- ) t1
1.使用方式上的差別。
where stu.xh not in
where ont exits
exists是不需要加上字段名字的。
有時候你會發現,運行好像沒問題。
但是,它還是存在的問題的!數值也行有時候是正確的。這可能誤導的!
- select count(*) from (
- ( select sc.xh from "JISUANJI"."STUDENTCHECK" sc )
- union
- ( select stu.XH as xh
- from "JISUANJI"."CVARIABLE" cv , "JISUANJI"."SEMESTER" s , "JISUANJI"."STUBASICINFO" stu , "JISUANJI"."COURSE" c,"JISUANJI"."SCOURSE" sc
- where cv.SID = s.SID and cv.SCID = sc.SCID and sc.xkkh = c.coursecode and cv.XH = stu.XH and 1=1
- and ( <span style="color:#ff0000;">not exists (select sc.xh from "JISUANJI"."STUDENTCHECK" sc where stu.xh= sc.xh</span>))
- )
- ) t1
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模式不一樣的地方是:返回值是真或假,是真就輸出。