ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 请教一个sql的优化

请教一个sql的优化

原创 Linux操作系统 作者:tigersun 时间:2007-11-08 17:08:00 0 删除 编辑
发现一条sql 语句disk reads很高,察看执行计划,发现对两表均是全表扫描,查看索引,学生选课表的“开始时间和结束时间”两个字段上有索引,且开始时间位于索引字段第一列,学生信息表的注册时间上有个单独的索引。
select count(distinct a.帐号id) num
from 学生选课表 b, 学生信息表 a  
where  a.帐号id =b.学生帐号id   
and a.注册时间 >=to_date('2006-11-01 00:00:00','yyyy-mm-dd hh24:mi:ss')   
and a.注册时间 <=to_date('2007-10-31 23:59:59','yyyy-mm-dd hh24:mi:ss')   
and b.开始时间 >=to_date('2006-11-01 00:00:00','yyyy-mm-dd hh24:mi:ss')   
and b.开始时间 <=to_date('2007-10-31 23:59:59','yyyy-mm-dd hh24:mi:ss')   
and  b.状态='正学习'
and b.标记=0

我以为没有使用索引是distinct引起,于是改成下面的形式:

select   count(a.帐号id) num
from 学生信息表 a   
where exists( select   'X'   
              from 学生选课表 b
              where b.学生帐号id = a.帐号id
              and b.开始时间 >=to_date('2006-11-01 00:00:00','yyyy-mm-dd hh24:mi:ss')
              and b.开始时间 <=to_date('2007-10-31 23:59:59','yyyy-mm-dd hh24:mi:ss')
              and b.标记=0
              and b.状态='正学习'
             )
and a.注册时间 >=to_date('2006-11-01 00:00:00','yyyy-mm-dd hh24:mi:ss')
and a.注册时间 <=to_date('2007-10-31 23:59:59','yyyy-mm-dd hh24:mi:ss');

结果仍然是 table access full  然后我又使用hint 提示
select  /*+index(学生信息表)*/ count(a.帐号id) num
from 学生信息表 a   
where exists( select   'X'   
              from 学生选课表 b
              where b.学生帐号id = a.帐号id
              and b.开始时间 >=to_date('2006-11-01 00:00:00','yyyy-mm-dd hh24:mi:ss')
              and b.开始时间 <=to_date('2007-10-31 23:59:59','yyyy-mm-dd hh24:mi:ss')
              and b.标记=0
              and b.状态='正学习'
             )
and a.注册时间 >=to_date('2006-11-01 00:00:00','yyyy-mm-dd hh24:mi:ss')
and a.注册时间 <=to_date('2007-10-31 23:59:59','yyyy-mm-dd hh24:mi:ss');

结果仍然是 table access full ,真头痛,这种语句该怎么优化,请高人指点?

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/310745/viewspace-6319/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2007-12-26

  • 博文量
    31
  • 访问量
    27266