南通颐猩文化传播有限公司

當(dāng)前位置:首頁(yè) >  站長(zhǎng) >  數(shù)據(jù)庫(kù) >  正文

詳解sql中exists和in的語(yǔ)法與區(qū)別

 2021-03-02 17:15  來(lái)源: 腳本之家   我來(lái)投稿 撤稿糾錯(cuò)

  域名預(yù)訂/競(jìng)價(jià),好“米”不錯(cuò)過(guò)

這篇文章主要介紹了sql中exists和in的語(yǔ)法與區(qū)別,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

exists和in的區(qū)別很小,幾乎可以等價(jià),但是sql優(yōu)化中往往會(huì)注重效率問(wèn)題,今天咱們就來(lái)說(shuō)說(shuō)exists和in的區(qū)別。

exists語(yǔ)法:

select … from table where exists (子查詢)

將主查詢的結(jié)果,放到子查詢結(jié)果中進(jìn)行校驗(yàn),如子查詢有數(shù)據(jù),則校驗(yàn)成功,那么符合校驗(yàn),保留數(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語(yǔ)句等價(jià)于select tname from teacher

(主查詢數(shù)據(jù)存在于子查詢,則查詢成功(校驗(yàn)成功))

此sql返回為空,因?yàn)樽硬樵儾⒉淮嬖谶@樣的數(shù)據(jù)。

in語(yǔ)法:

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的語(yǔ)法與區(qū)別的文章就介紹到這了,更多相關(guān)sql中exists和in語(yǔ)法區(qū)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

來(lái)源:腳本之家

鏈接:https://www.jb51.net/article/203457.htm

申請(qǐng)創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!

相關(guān)文章

熱門(mén)排行

信息推薦