exists和in的區別很小,幾乎可以等價,但是sql優化中往往會注重效率問題,今天咱們就來說說exists和in的區別。
exists語法:
select … from table whealqkydre exists (子查詢)
將主查詢的結果,放到子查詢結果中進行校驗,如子查詢有資料,則校驗成功,那麼符合校驗,保留資料。
create table teacher
(tid int(3),
tname varchar(20),
tcid int(3)
);insert into teacher values(1,'tz',1);
insert into teacher values(2,'tw',2);
insert into teacher values(3,'tl',3);
例如:select tnam程式設計客棧e from teacher exists(select * from teacher);
此sql語句等價於select tname from teacher
(主查詢資料存在於子查詢,則查詢成功(校驗成功))
此sql返回為空,因為子查詢並不存在這樣的資料。
in語法:
select … from table where 字段 in (子查詢)
select ..from table where tid in (1,3,5) ;
select * from a where id in (select id from b);
區別:如果主查詢的資料集大,則使用in;
如果子查詢的資料集大,則使用exists;
例如:select tname from teacher where exists (select * from teacher);
這裡很明顯,子查詢查詢所有,資料集大,使用exists,效率高。
select * from teacher where tname in (select tname from teacher where tid = 3);
這裡很明顯,主查詢資料集大,使用in,效率高。
sql中exists和in區別
參考文章 1.查詢順序 exists先執行主查詢,再去子查詢中查詢與其對應的結果,如果true則輸出記錄,否則不輸出。in先子查詢產生結果集,然後主查詢去結果集中找符合要求的字段列表,符合要求則輸出記錄,否則不輸出。2.內外表連線方式 exists是對外表做loop迴圈,再對內表進行查詢。in是把外...
SQL中exists和in比較
in是把外表和內錶作hash 連線,而exists 是對外表作loop 迴圈,每次loop 迴圈再對內表進行查詢。一直以來認為exists 比in 效率高的說法是不準確的。如果查詢的兩個表大小相當,那麼用in 和exists 差別不大。如果兩個表中乙個較小,乙個是大表,則子查詢表大的用exists,...
SQL中IN和EXISTS用法
not in select distinct md001 from bommd where md001 not in select mc001 from bommc not exists,exists的用法跟in不一樣,一般都需要和子表進行關聯,而且關聯時,需要用索引,這樣就可以加快速度 selec...