数据库中in exists的主要作用和区别

in,exists其实是两个功能差不多的sql命令,如果查询的两个表大小相当,用in和exists差别不大。

in查询相当于多个or条件的叠加,这个相信大家都比较容易理解
exists则主要用于主表的结果集小,也就是外层循环少的情况,而in是用于子查询的结果集少的情况。
exists查询时对主表(外表)用loop逐条循环查询,每次查询都会判断exists的条件语句,当 exists里的条件语句能够返回记录行时(注:无论记录行是多少,只要能返回),条件就为真,则外循环LOOP返回当前loop到的这条记录,反之如果exists里的条 件语句不能返回记录行,则当前loop到的这条记录被丢弃,exists的条件就像一个bool条件,当能返回结果集则为true,不能返回结果集则为 false.
 
如果关联查询两个表中一个小表,一个大表,则子查询表大的用exists,子查询表小的用in: 
例如:表A(小表),表B(大表)
select * from A where cc in (select cc from B) 效率低,用到了A表上cc列的索引;
select * from A where exists(select cc from B where cc=A.cc) 效率高,用到了B表上cc列的索引。 
相反的
select * from B where cc in (select cc from A) 效率高,用到了B表上cc列的索引;
select * from B where exists(select cc from A where cc=B.cc) 效率低,用到了A表上cc列的索引。

需要注意的:
in查询的子条件返回结果必须只有一个字段,例如
select * from user where userId in (select id from B);
而不能是
select * from user where userId in (select id, age from B);
而exists就没有这个限制
总的来说,
如果A表有n条记录,那么exists查询就是将这n条记录逐条取出,然后判断n遍exists括号中的条件语句是否为真,为真则返回当前这条记录,否则丢弃
而in查询则相当于多个or条件的叠加,且效率一样,
例如:
select * from TABLE1 where userId in (1, 2, 3);
等同于:
select * from user where userId = 1 or userId = 2 or userId = 3;

如果是单表查询,很显然in是最佳唯一选择,Exists会弄的更复杂而且几乎很难实现

比如最简单的
select * from K_Micfo where Loginname IN('张小明', '王大锤')
用exists是很难实现上面这个简单功能的。exists一般用于多表条件判断。必须要引用第二张表来做为条件,如果这里非得用exists实现,则要使用自表关联方式来处理,语句如下:
select * from K_Micfo t1 where exists (select 'x' from K_Micfo t2 where t2.loginid=t1.loginid and (t1.loginname='张小明' or t1.loginname='王大锤'))

参考地址:https://www.cnblogs.com/xianlei/p/8862313.html

posted @ 2022-10-04 00:14  IT情深  阅读(41)  评论(0编辑  收藏  举报