Mysql中⽤exists代替in
exists对外表⽤loop逐条查询,每次查询都会查看exists的条件语句,当 exists⾥的条件语句能够返回记录⾏时(⽆论记录⾏是的多少,只要能返回),条件就为真,返回当前loop到的这条记录,反之如果exists⾥的条件语句不能返回记录⾏,则当前loop到的这条记录被丢弃,exists 的条件就像⼀个bool条件,当能返回结果集则为true,不能返回结果集则为 false
如下:
select * from user where exists (select 1);
对user表的记录逐条取出,由于⼦条件中的select 1永远能返回记录⾏,那么user表的所有记录都将被加⼊结果集,所以与 select * from user;是⼀样的
⼜如下
select * from user where exists (select * from user where userId = 0);
可以知道对user表进⾏loop时,检查条件语句(select * from user where userId = 0),由于userId永远不为0,所以条件语句永远返回空集,条件永远为false,那么user表的所有记录都将被丢弃
not exists与exists相反,也就是当exists条件有结果集返回时,loop到的记录将被丢弃,否则将loop到的记录加⼊结果集
总的来说,如果A表有n条记录,那么exists查询就是将这n条记录逐条取出,然后判断n遍exists条件
in查询相当于多个or条件的叠加,这个⽐较好理解,⽐如下⾯的查询
select * from user where userId in (1, 2, 3);
等效于
select * from user where userId = 1 or userId = 2 or userId = 3;
not in与in相反,如下
select * from user where userId not in (1, 2, 3);
等效于
select * from user where userId != 1 and userId != 2 and userId != 3;
总的来说,in查询就是先将⼦查询条件的记录全都查出来,假设结果集为B,共有m条记录,然后在将⼦查询条件的结果集分解成m个,再进⾏m次查询
值得⼀提的是,in查询的⼦条件返回结果必须只有⼀个字段,例如
select * from user where userId in (select id from B);
⽽不能是
select * from user where userId in (select id, age from B);
⽽exists就没有这个限制
下⾯来考虑exists和in的性能
考虑如下SQL语句
1: select * from A where exists (select * from B where B.id = A.id);
2: select * from A where A.id in (select id from B);
查询1.可以转化以下伪代码,便于理解
for ($i = 0; $i < count(A); $i++) {
  $a = get_record(A, $i); #从A表逐条获取记录
  if (B.id = $a[id]) #如果⼦条件成⽴
    $result[] = $a;
}
return $result;
⼤概就是这么个意思,其实可以看到,查询1主要是⽤到了B表的索引,A表如何对查询的效率影响应该不⼤
假设B表的所有id为1,2,3,查询2可以转换为
select * from A where A.id = 1 or A.id = 2 or A.id = 3;
这个好理解了,这⾥主要是⽤到了A的索引,B表如何对查询影响不⼤
下⾯再看not exists 和 not in
1. select * from A where not exists (select * from B where B.id = A.id);
2. select * from A where A.id not in (select id from B);
看查询1,还是和上⾯⼀样,⽤了B的索引
⽽对于查询2,可以转化成如下语句
select * from A where A.id != 1 and A.id != 2 and A.id != 3;
可以知道not in是个范围查询,这种!=的范围查询⽆法使⽤任何索引,等于说A表的每条记录,都要在B表⾥遍历⼀次,查看B表⾥是否存在这条记录
故not exists⽐not in效率⾼
mysql中的in语句是把外表和内表作hash 连接,⽽exists语句是对外表作loop循环,每次loop循环再对内表进⾏查询。⼀直⼤家都认为exists ⽐in语句的效率要⾼,这种说法其实是不准确的。这个是要区分环境的。
如果查询的两个表⼤⼩相当,那么⽤in和exists差别不⼤。
如果两个表中⼀个较⼩,⼀个是⼤表,则⼦查询表⼤的⽤exists,⼦查询表⼩的⽤in:
exists子查询例如:表A(⼩表),表B(⼤表)
1:
select * from A where cc in (select cc from B) 效率低,⽤到了A表上cc列的索引;
select * from A where exists(select cc from B where ) 效率⾼,⽤到了B表上cc列的索引。
相反的
2:
select * from B where cc in (select cc from A) 效率⾼,⽤到了B表上cc列的索引;
select * from B where exists(select cc from A where ) 效率低,⽤到了A表上cc列的索引。
not in 和not exists如果查询语句使⽤了not in 那么内外表都进⾏全表扫描,没有⽤到索引;⽽not extsts 的⼦查询依然能⽤到表上的索引。所以⽆论那个表⼤,⽤not exists都⽐not in要快。
in 与 =的区别
select name from student where name in ('zhang','wang','li','zhao');
select name from student where name='zhang' or name='li' or name='wang' or name='zhao'
的结果是相同的。