`
dacoolbaby
  • 浏览: 1262561 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

EXSITS应该怎么用?

阅读更多
   无论是做项目还是普通使用SQL,我们通常都会使用IN。因为很好理解,也很方便。但是,面对着多层查询嵌套,或者IN关键字里面的结果集数量巨大,查询的效率就会直线下降。这时候,我们应该用好EXSITS。

首先,来一个简单的例子。
with score(id,name,subject,score)
as(
select 0,'张三','数学',88 from dual union all
select 1,'张三','英语',78 from dual union all
select 2,'李四','数学',68 from dual union all
select 3,'李四','英语',98 from dual union all
select 4,'王五','数学',77 from dual union all
select 5,'王五','英语',92 from dual union all
select 6,'赵六','数学',81 from dual union all
select 7,'赵六','英语',75 from dual
)
,has_phone(name,has_phone)
as(
select '张三','有' from dual union all
select '李四','没有' from dual union all
select '王五','没有' from dual union all
select '赵六','有' from dual 
)
--select *
--  from score a
-- where name in (select name from has_phone where has_phone = '有')
select *
  from score a
 where exists (select 1
          from has_phone b
         where b.name = a.name
           and has_phone = '有')

这段SQL的意思是,查询有手机的同学的成绩。

那么我来理解一下IN和EXSITS的区别吧。
在使用IN的时候。
数据库首先是去在has_phone里面查找所有条件为“有”的name。
然后把这些结果集让每一个name去匹配。

在使用EXSITS的时候。
数据库是先查询SCORE,然后每个连接条件到EXSITS里面进行判断。
如果为TRUE,则加入结果集,否则就跳过。

EXSITS执行过程
可以理解为:
for x in (select * from score a)
loop

if(exists(select 1 from has_phone b where b.name = a.name ))
then
  output the record;
end if;

end loop;

对于in 和 exists的性能区别:
如果子查询得出的结果集记录较少,主查询中的表较大且又有索引时应该用in;
反之如果外层的主查询记录较少,子查询中的表大,又有索引时使用exists.
其实我们区分in和exists主要是造成了驱动顺序的改变(这是性能变化的关键),如果是exists,
那么以外层表为驱动表,先被访问,如果是IN,那么先执行子查询,所以我们会以驱动表的快速返回为目标,
那么就会考虑到索引及结果集的关系了








分享到:
评论

相关推荐

    sqlserver中判断表或临时表是否存在

    判断数据表是否存在可以使用两种方法。 方法一:使用 object_id 函数 使用 `object_id` 函数可以判断数据表是否存在,语法如下: ```sql IF OBJECT_ID('tablename', 'U') IS NOT NULL PRINT '存在' ELSE PRINT '...

    sqlserver exists,not exists的用法

    在SQL Server中,`EXISTS` 和 `NOT EXISTS` 是两个非常重要的子句,用于在查询中检查子查询是否返回任何记录。...在实际应用中,根据具体需求选择使用哪一个,可以有效地优化查询性能和结果的准确性。

    数据库设计开发规范-阿里.pdf

    ="、"notin"、"exsits"和"notexists"等。 - **格式规范**: 注释说明清晰;统一缩进风格;合理断行。 ##### MySQL - **编码规范**: 使用SQL操作数据库前,必须由useDB_name开始;如果需要事务支持,关闭自动提交;...

    MySQL查询优化

    4 in和exsits优化 5 count(*)查询优化 笔者使用的MySQL版本是8.0.13。 1 索引优化 《MySQL索引优化》 2 分页查询优化 很多时候我们业务系统实现分页功能可能会用如下sql实现: select * from employees limit ...

    Redis的持久化存储redis-storage.zip

    ds:error_if_exists 0 //if the opened database exsits will throw exception ds:paranoid_checks 0 ds:block_cache_size 10000 ds:write_buffer_size 100000000 //写缓存大小 ds:block_size 4096 ds:max_open_...

    传感技术中的解析水温水位传感器

    关键词:传感器 高温 密封 水垢 干扰abstract:This text analyzed the water temperature water level primarily to spread the machine that feels now the some problem exsits, and put forward the homologous ...

Global site tag (gtag.js) - Google Analytics