1. 程式人生 > 其它 >sql中exists和in的語法與區別

sql中exists和in的語法與區別

技術標籤:java開發mysqlsql優化mysqlmysql優化java

exists和in的區別很小,幾乎可以等價,但是sql優化中往往會注重效率問題,今天咱們就來說說exists和in的區別。
exists語法:
select … from table where 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 tname from teacher exists(select * from teacher);

此sql語句等價於select tname from teacher
(主查詢資料存在於子查詢,則查詢成功(校驗成功))

select tname from teacher where exists (select * from teacher where tid =9999) ;

此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,效率高。