首页 > 数据库 > Oracle > 正文

ORACLE SQL性能优化系列 (四)

2024-08-29 13:31:13
字体:
来源:转载
供稿:网友

最大的网站源码资源下载站,


 

13.       计算记录条数

     和一般的观点相反, count(*) 比count(1)稍快 , 当然如果可以通过索引检索,对索引列的计数仍旧是最快的. 例如 count(empno)

 

(译者按: 在csdn论坛中,曾经对此有过相当热烈的讨论, 作者的观点并不十分准确,通过实际的测试,上述三种方法并没有显著的性能差别)

 

14.       用where子句替换having子句

 

     避免使用having子句, having 只会在检索出所有记录之后才对结果集进行过滤. 这个处理需要排序,总计等操作. 如果能通过where子句限制记录的数目,那就能减少这方面的开销.

 

例如:

 

     低效:

     select region,avg(log_size)

     from location

     group by region

     having region region != ‘sydney’

     and region != ‘perth’

 

     高效

     select region,avg(log_size)

     from location

     where region region != ‘sydney’

     and region != ‘perth’

     group by region

(译者按: having 中的条件一般用于对一些集合函数的比较,如count() 等等. 除此而外,一般的条件应该写在where子句中)

 

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 多个column 例子:

     低效:

           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,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;

 

(译者按: 经常在论坛中看到如 ’能不能用一个sql写出….’ 的贴子, 殊不知复杂的sql往往牺牲了执行效率. 能够掌握上面的运用函数解决问题的方法在实际工作中是非常有意义的)

 

 (待续)
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表