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

Oracle语句优化(五)

原创 水煮鱼 2022-08-14
402

15、减少对表的查询

在含有子查询的 SQL 语句中,要特别注意减少对表的查询。

例如:

低效:

select tab_name

from tables

where tab_name = (select tab_name from tab_columns where version = 604)

and db_ver = (select db_ver from tab_columns where version = 604);

高效:

select tab_name

from tables

where (tab_name, db_ver) = (select tab_name, db_ver) from tab_columns

where version = 604);

低效:

update emp

set emp_cat = (select max(category) from emp_categories),

sal_range = (select max(sal_range) from emp_categories)

where emp_dept = 0020;

高效:

update emp

set (emp_cat, sal_range) = (select max(category), max(sal_range)

from emp_categories)

where emp_dept = 0020; 16、通过内部函数提高 SQL 效率

select h.empno, e.ename, h.hist_type, t.type_desc, count(*)

from history_type t, emp e, emp_history h

where h.empno = e.empno

and h.hist_type = t.hist_type

group by h.empno, e.ename, h.hist_type, t.type_desc;

通过调用下面的函数可以提高效率。

function lookup_hist_type(typ in number) return varchar2 as

tdesc varchar2(30);

cursor c1 is

select type_desc from history_type where hist_type = typ;

begin

open c1;

fetch c1

into tdesc;

close c1;

return(nvl(tdesc, '?'));

end;

function lookup_emp(emp in number) return varchar2 as

ename varchar2(30);

cursor c1 is

select ename from emp where empno = emp;

begin

open c1;

fetch c1

into ename;

close c1;

return(nvl(ename, '?'));

end;

select h.empno,

select h.empno,

lookup_emp(h.empno),

h.hist_type,

lookup_hist_type(h.hist_type),

count(*)

from emp_history h

group by h.empno, h.hist_type;

17、使用表的别名(Alias)

当在 SQL 语句中连接多个表时,请使用表的别名并把别名前缀于每个 Column 上。这

样一来,就可以减少解析的时间并减少那些由 Column 歧义引起的语法错误。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'); 

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

评论