暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle语句优化(六)

原创 水煮鱼 2022-08-15
627

18、用 EXISTS 替代 IN
在许多基于基础表的查询中,为了满足一个条件,往往需要对另一个表进行联接。在这
种情况下,使用 EXISTS(或 NOT EXISTS)通常将提高查询的效率。
低效:
select *
from emp –-基础表
where empno > 0
and deptno in (select deptno from dept where loc = 'MELB');
高效:
select *
from emp –-基础表
where empno > 0
and exists (select 'X'
from dept
where dept.deptno = emp.deptno
and loc = 'MELB');
19、用 NOT EXISTS 替代 NOT IN
在子查询中, NOT IN 子句将执行一个内部的排序和合并。无论在哪种情况下, NOT IN
都是最低效的,因为它对子查询中的表执行了一个全表遍历。为了避免使用 NOT IN,我们
可以把它改写成外连接 Outer Joins,或 NOT EXISTS。
例如:
select *
from emp
where dept_no not in (select dept_no from dept where dept_cat = 'A');
为了提高效率,改写为:
高效:
select *
from emp a, dept b
where a.dept_no = b.dept(+)
and b.dept_no is null
and b.dept_cat(+) = 'A';
最高效:
select *
from emp e
where not exists (select 'X'
from dept d
where d.dept_no = e.dept_no
and dept_cat = 'A');
20、用表连接替换 EXISTS
通常来说,采用表连接的方式比 EXISTS 更有效率。
例如:
低效:
select ename
from emp e
where exists (select 'X'
from dept
where dept_no = e.dept_no
and dept_cat = 'A');
高效:
select ename
from dept d, emp e
where e.dept_no = d.dept_no
and dept_cat = 'A';
在 RBO 的情况下,前者的执行路径包括 FILTER,后者使用 NESTED LOOP。
21、用 EXISTS 替换 DISTINCT
当提交一个包含一对多表信息(比如部门表和雇员表)的查询时,避免在 SELECT 子句
中使用 DISTINCT。一般可以考虑用 EXIST 替换。
例如:
低效:
select distinct dept_no, dept_name
from dept d, emp e
where d.dept_no = e.dept_no;
高效:
select dept_no, dept_name
from dept d
where exists (select 'X' from emp e where e.dept_no = d.dept_no);
EXISTS 使查询更为迅速,因为 RDBMS 核心模块将在子查询的条件一旦满足后,立刻
返回结果。  

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论