詳解sql中exists和in的語法與區(qū)別
exists和in的區(qū)別很小,幾乎可以等價,但是sql優(yōu)化中往往會注重效率問題,今天咱們就來說說exists和in的區(qū)別。
exists語法:
select … from table where exists (子查詢)
將主查詢的結(jié)果,放到子查詢結(jié)果中進行校驗,如子查詢有數(shù)據(jù),則校驗成功,那么符合校驗,保留數(shù)據(jù)。
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 tname from teacher exists(select * from teacher);
此sql語句等價于select tname from teacher
(主查詢數(shù)據(jù)存在于子查詢,則查詢成功(校驗成功))
此sql返回為空,因為子查詢并不存在這樣的數(shù)據(jù)。
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);
區(qū)別:
如果主查詢的數(shù)據(jù)集大,則使用in;
如果子查詢的數(shù)據(jù)集大,則使用exists;
例如:
select tname from teacher where exists (select * from teacher);
這里很明顯,子查詢查詢所有,數(shù)據(jù)集大,使用exists,效率高。
select * from teacher where tname in (select tname from teacher where tid = 3);
這里很明顯,主查詢數(shù)據(jù)集大,使用in,效率高。
到此這篇關(guān)于sql中exists和in的語法與區(qū)別的文章就介紹到這了,更多相關(guān)sql中exists和in語法區(qū)別內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。