两个独立的Oracle视图运行速度很快,但组合时速度极慢

时间:2018-02-05 07:08:28

标签: sql oracle performance select views

我有两个单独的视图在Oracle中返回数据。独立使用视图的查询效果很好但是同时使用两个视图的查询非常慢。这是一个例子:

create view masterview as 
select masterno,detailno from mastertable;

create view detailview as 
select detailno,field1,field2 from detailtable;

MasterTable在MasterNo上有一个索引,而DetailTable在DetailNo上有一个索引。

select * from masterview 
where masterno = 1234; -- 0.429 seconds to run

select * from detailview 
where detailno in (10,20,30); -- 0.251 seconds to run

select * from DetailView 
where DetailNo in (Select DetailNo from MasterView 
                   where MasterNo = 1234); -- 407.057 seconds to run

我尝试过使用多种方法,但没有一种方法有所作为。如何让组合查询快速运行?

问题似乎与视图有关。我可以消除第二个视图,我可以消除IN并且问题仍然存在:

select d.*
  from detailview d, testtable t
 where t.masterno = 1234
   and d.detailno = t.detailno;
-- DetailTable used by DetailView is indexed on DetailNo.
-- TestTable is indexed on MasterNo
-- TestTable contains two fields MasterNo,DetailNo
-- This takes 100's of seconds to run

select d.*
  from detailtable d, testtable t
 where t.masterno = 1234
   and d.detailno = t.detailno;
-- This runs in less than a second.

2 个答案:

答案 0 :(得分:1)

尝试使用INNER JOIN代替IN。也许,由于IN

,您的查询效果会变慢
select d.* 
from DetailView as d
inner join MasterView  as m 
  on d.DetailNo = m.DetailNo AND  m.MasterNo = 1234;

答案 1 :(得分:0)

我不确定,但你可以试试这个:

select d.* 
  from MasterView m, DetailView d
 where m.MasterNo = 1234
   and m.DetailNo = d.DetailNo
;

如果DetailNo在mastertable非唯一中,请使用distinct

select distinct d.* ...