比較使用 EXISTS 和 IN 的查詢

2021-06-19 17:37:05 字數 875 閱讀 4673

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

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

相反的2:

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

not in 和not exists

如果查詢語句使用了not in 那麼內外表都進行

全表掃瞄,沒有用到索引;

而not exists 的

子查詢依然能用到表上的索引。

所以無論哪個表大,用not exists都比not in要快。

in 與 =的區別

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

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

的結果是相同的。

示例:查詢表1中在表2中是否按fid是否存在。

select * from 表名 t1

where exists

(select fid from 表名 t2 where t1.fid=t2.fid)

比較使用 EXISTS 和 IN 的查詢

sql codein和existsin 是把外表和內錶作hash 連線,而exists是對外表作loop迴圈,每次loop迴圈再對內表進行查詢。一直以來認為exists比in效率高的說法是不準確的。如果查詢的兩個表大小相當,那麼用in和exists差別不大。全文 in和existsin 是把外表和內...

in 和 exists的比較

系統要求進行sql優化,對效率比較低的sql進行優化,使其執行效率更高,其中要求對sql中的部分in not in修改為exists not exists 修改方法如下 in的sql語句 select id,category id,htmlfile,title,convert varchar 20 ...

SQL中exists和in比較

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