1. 程式人生 > >in exist,not in ,not exist

in exist,not in ,not exist

轉自:https://www.cnblogs.com/tiantiansunny/p/3555986.html

A: In:是把外表和內表做Hash 連線,而exists 是對外表作loop 迴圈,每次loop迴圈再對內表進行查詢。

當查詢兩個表的大小相當時,用In 和 exists差別不大。

如果兩個表中一個表較小,一個表較大,那麼子查詢表大的用exists,子查詢表小的用In,效率會高的。

也就是說 IN適合於外表大而內表小的情況;EXISTS適合於外表小而內表大的情況,這樣效率會高的

例如 :表a(小表),表b(大表)

1.select * from a where aid in (select aid from b) --->效率低:全程掃描b表,用到a 表上的aid的索引,因為a表小,b表大

    上面in的語句可以理解為:
    select * 
      from a, ( select distinct aid from b) b1
     where a.aid = b1.aid.

 

   select * from a where exists (select aid from b where b.aid = a.aid) --->效率高: 全程掃描a表,用到b表上的aid的索引。因為b表大。

 上面的exists的語句可以理解為:

  for aid in ( select * from a)
    loop
       if ( exists ( select aid from b where b.aid= a.aid )
       then 
          OUTPUT THE RECORD!
       end if
    end loop

2. select * from b where aid in (select aid from a)----效率高:全程掃描a 表,用到b表上的aid 索引

    select * from b where exists (select aid from a were a.aid= b.aid) --->效率低:全程掃描b 表:用到a 表上的aid索引。

B: Not in 和Not Exists 的 效率

如果查詢語句使用了Not In,那麼內外表全部進行掃描,沒有乃至索引

Not Exist用到子表中的索引進行查詢,所以無論兩個表中哪個表大,Not exists 都要比Not in 要快。