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

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

 2021-03-02 17:15  來源: 腳本之家   我來投稿 撤稿糾錯

  域名預(yù)訂/競價,好“米”不錯過

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

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)文章希望大家以后多多支持腳本之家!

來源:腳本之家

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

申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點子。點擊此處,共同探討創(chuàng)業(yè)新機遇!

相關(guān)文章

熱門排行

信息推薦