?
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 '
的結果是相同的。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
