2010-07-19 96 views
1

以下查询需要20秒才能运行。 user_table40054记录。 other_table14000记录如何使oracle for循环更快

select count(a.user_id) from user_table a, other_table b 
where a.user_id = b.user_id; 

我们的限制是,运行超过8秒无任何查询就会被杀死......> _ <我已经跑了解释计划,在这里问的问题,但根据我们的限制,我不能让这个查询运行时间少于8秒。所以我制定了一个循环。

begin 
FOR i IN role_user_rec.FIRST .. role_user_rec.LAST LOOP 
      SELECT COUNT (a.user_id) INTO v_into FROM user_table a 
      WHERE TRIM(role_user_rec(i).user_id) = TRIM(a.user_id); 
      v_count := v_count + v_into; 
END LOOP; 

我知道限制吸吮,这是不是effecient的方式做事情,但是否有其他方法,使这个循环运行速度更快?

+0

您可能会考虑发布您的查询的解释计划。 – EvilTeach 2010-07-19 15:37:06

+0

这是如何执行的?:从user_table中选择count(*)a其中a.user_id在(从user_id选择其他user_id不为null的user_id) – 2010-07-19 15:38:13

+2

role_user_rec来自哪里?如果这是另一个查询的结果,那么也许这两个可以联合起来给你一个单一的查询....以及什么样的数据类型是role_user_rec(i).user_id和user_table.user_id? – 2010-07-19 15:39:16

回答

2

你可以绕过循环吗?我同意Janek的观点,如果查询本身花费太长时间,您可能需要采取其他方法来获取它。同意马克,如果你可以在一个查询中做到这一点,那么一定要这样做。但是,如果你不能,像下面那样放下回路

但是试试这样的东西;删除循环:

/* 
--set up for demo/test 
Create Type Testusertype As Object(User_Id Number , User_Name Varchar2(500)); 
CREATE TYPE TESTUSERTYPETABLE IS TABLE OF TESTUSERTYPE; 
*/ 

Declare 
    Tutt Testusertypetable; 
    TOTALCOUNT NUMBER ; 
Begin 

    Select Testusertype(Object_Id,Object_Name) 
     bulk collect into TUTT 
     From User_Objects 
    ; 

Dbms_Output.Put_Line(Tutt.Count); 

Select Count(*) Into Totalcount 
    From User_Objects Uu 
     Inner Join Table(Tutt) T 
     ON T.User_Id = Uu.Object_Id; 

Dbms_Output.Put_Line(Tutt.Count); 
Dbms_Output.Put_Line(Totalcount); 

End ;