我如何使SQL查询更快地工作

时间:2016-03-23 06:23:10

标签: sql oracle oracle11g

select * from student@LINK1 
where id in(select id from classs@LINK1 where a_id in 
             (select id from desk@LINK1 where USN in (1,2,3,4,5,6)))
               and id not in 
                 (select id from student where id in 
                   (select id from classs where a_id in 
                     (select id from desk where USN in (1,2,3,4,5,6))));

上述查询需要15分钟才能获取数据。 任何人都可以帮助我如何让它更快地运作

1 个答案:

答案 0 :(得分:0)

要比较200k行,你必须确保你没有做嵌套循环:

select /*+use_hash(remot local)*/
    remot.*
from (
     select * from student@LINK1 
     where id in(select id from classs@LINK1 where a_id in 
                   (select id from desk@LINK1 where USN in (1,2,3,4,5,6)))
     ) remot
left join
      (select id from student where id in 
             (select id from classs where a_id in 
                     (select id from desk where USN in (1,2,3,4,5,6)))
      ) local
on local.id = remot.id
where local.id is null;

编辑:阅读评论后,我认为重写查询可能值得:

select * 
from student@LINK1 
where id in 
   (
     select id 
     from classs@LINK1 
     where a_id in 
              (select id from desk@LINK1 where USN in (1,2,3,4,5,6))
           and id not in
                    (select id from classs where a_id in 
                       (select id from desk where USN in (1,2,3,4,5,6))
    )
;

因为它会超过一些联接。此查询中的not in也可能会重写为left join