2019-02-12
閱讀量:
877
mysql in和exists的用法有什么異同?
問題描述:
mysql查詢中,經(jīng)常使用到in函數(shù),那么和它具有類似功能的exists在使用上有什么區(qū)別呢?兩者的適用范圍又是什么?
解決思路:
create table test(score varchar(10));
insert test_new values('A'),('B');
create table test_new(score varchar(10));
insert test_new values('A'),('B'),('C'),('D');
- 如果要查詢test中和test_new相同的數(shù)據(jù),可以用in來表示
select * from test where score in (select score from test_new);
- 也可以用exists來表示
select * from test a where exists (select score from test_new where score=a.score);
- 要注意exists是緊跟著where語句的,沒有score限定字段
- exists表示的是(子查詢)中的布爾值,運(yùn)行邏輯是先主查詢一次,再每一行執(zhí)行一次子查詢,如果true則最后整合輸出
適用范圍來看,兩者功能接近,但是效率不同:
- 子查詢的表大用exist效率高
- 涉及not in 或者 not exists的時(shí)候,后者效率高






評論(0)


暫無數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評論
1條評論
0條評論