2019-02-12
阅读量:
829
mysql in和exists的用法有什么异同?
问题描述:
mysql查询中,经常使用到in函数,那么和它具有类似功能的exists在使用上有什么区别呢?两者的适用范围又是什么?
解决思路:
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相同的数据,可以用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表示的是(子查询)中的布尔值,运行逻辑是先主查询一次,再每一行执行一次子查询,如果true则最后整合输出
适用范围来看,两者功能接近,但是效率不同:
- 子查询的表大用exist效率高
- 涉及not in 或者 not exists的时候,后者效率高






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
0条评论