如果查詢的兩個(gè)表大小相當(dāng),那么用in和exists差別不大想暗。
如果兩個(gè)表中一個(gè)較小妇汗,一個(gè)是大表,則子查詢表大的用exists江滨,子查詢表小的用in:
例如:表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如果查詢語(yǔ)句使用了not in 那么內(nèi)外表都進(jìn)行全表掃描懂牧,沒(méi)有用到索引;而not extsts 的子查詢依然能用到表上的索引。所以無(wú)論那個(gè)表大僧凤,用not exists都比not in要快畜侦。
in 與 =的區(qū)別
**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' **
的結(jié)果是相同的。