首页 > 数据库 > Oracle > 正文

ORACLE SQL性能优化系列 (二)

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

4. 选择最有效率的表名顺序(只在基于规则的优化器中有效)

oracle的解析器按照从右到左的顺序处理from子句中的表名,因此from子句中写在最后的表(基础表 driving table)将被最先处理. 在from子句中包含多个表的情况下,你必须选择记录条数最少的表作为基础表.当oracle处理多个表时, 会运用排序及合并的方式连接它们.首先,扫描第一个表(from子句中最后的那个表)并对记录进行派序,然后扫描第二个表(from子句中最后第二个表),最后将所有从第二个表中检索出的记录与第一个表中合适记录进行合并.

 

例如:

     表 tab1 16,384 条记录

     表 tab2 1      条记录

 

     选择tab2作为基础表 (最好的方法)

     select count(*) from tab1,tab2   执行时间0.96秒

    

    选择tab2作为基础表 (不佳的方法)

     select count(*) from tab2,tab1   执行时间26.09秒

 

如果有3个以上的表连接查询, 那就需要选择交叉表(intersection table)作为基础表, 交叉表是指那个被其他表所引用的表.

 

例如:

 

   emp表描述了location表和category表的交集.

 

 select *

from location l ,

      category c,

      emp e

where e.emp_no between 1000 and 2000

and e.cat_no = c.cat_no

and e.locn = l.locn

 

将比下列sql更有效率

 

select *

from emp e ,

location l ,

      category c

where  e.cat_no = c.cat_no

and e.locn = l.locn

and e.emp_no between 1000 and 2000

 

 

5.       where子句中的连接顺序.

 

oracle采用自下而上的顺序解析where子句,根据这个原理,表之间的连接必须写在其他where条件之前, 那些可以过滤掉最大数量记录的条件必须写在where子句的末尾.

 

例如:

 

(低效,执行时间156.3秒)

select …

from emp e

where  sal > 50000

and    job = ‘manager’

and    25 < (select count(*) from emp

             where mgr=e.empno);

 

(高效,执行时间10.6秒)

select …

from emp e

where 25 < (select count(*) from emp

             where mgr=e.empno)

and    sal > 50000

and    job = ‘manager’;

 

 

6.     select子句中避免使用 ‘ * ‘

当你想在select子句中列出所有的column时,使用动态sql列引用 ‘*’ 是一个方便的方法.不幸的是,这是一个非常低效的方法. 实际上,oracle在解析的过程中, 会将’*’ 依次转换成所有的列名, 这个工作是通过查询数据字典完成的, 这意味着将耗费更多的时间.

   

 

7.     减少访问数据库的次数

当执行每条sql语句时, oracle在内部执行了许多工作: 解析sql语句, 估算索引的利用率, 绑定变量 , 读数据块等等. 由此可见, 减少访问数据库的次数 , 就能实际上减少oracle的工作量.

 

例如,

    以下有三种方法可以检索出雇员号等于0342或0291的职员.

 

方法1 (最低效)

    select emp_name , salary , grade

    from emp

    where emp_no = 342;

    

    select emp_name , salary , grade

    from emp

    where emp_no = 291;

 

方法2 (次低效)

   

    declare

        cursor c1 (e_no number) is

        select emp_name,salary,grade

        from emp

        where emp_no = e_no;

    begin

        open c1(342);

        fetch c1 into …,..,.. ;

        …..

        open c1(291);

       fetch c1 into …,..,.. ;

         close c1;

      end;

 

 

 

 

 

方法3 (高效)

 

    select a.emp_name , a.salary , a.grade,

            b.emp_name , b.salary , b.grade

    from emp a,emp b

    where a.emp_no = 342

    and   b.emp_no = 291;

 

 

注意:

    在sql*plus , sql*forms和pro*c中重新设置arraysize参数, 可以增加每次数据库访问的检索数据量 ,建议值为200

 

(待续)


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