如何在Oracle 11g中找到父级的所有子ID

时间:2015-12-09 00:09:49

标签: oracle oracle11g connect-by

我有一个id表,它在不同的表中有一个parentid,这在应用层构建了一个文件夹结构。我需要获取特定“根文件夹”

中所有ID的列表
select count(id)
from t1, t2
where t1.id=t2.id
connect by prior t1.id = t2.parentid
start with t1.id in (select id from t3 where name = 'Root Folder')
  

t1 = 4,102,065行

     

t2 = 48,965,392行

     

t3 是一个视图

     

t4 是存储t3中名称的基础表(仅在下面的解释计划中引用)

现在这会返回正确的结果,但需要3分41秒(计数为3,257,847)

有没有更好的方法来执行此类查询或是我唯一的选项索引?

这是解释计划,我已经替换了真实的表和索引名称以匹配上面的示例:

Plan
SELECT STATEMENT  ALL_ROWSCost: 14  Bytes: 20  Cardinality: 1                                   
17 SORT GROUP BY  Bytes: 20  Cardinality: 1                                 
    16 CONNECT BY WITH FILTERING                            
        10 NESTED LOOPS  Cost: 5  Bytes: 153  Cardinality: 3                        
            8 NESTED LOOPS  Cost: 4  Bytes: 27  Cardinality: 1                      
                6 VIEW VIEW SYS.VW_NSO_1 Cost: 2  Bytes: 10  Cardinality: 1                 
                    5 HASH UNIQUE  Bytes: 57  Cardinality: 1            
                        4 NESTED LOOPS  Cost: 2  Bytes: 57  Cardinality: 1          
                            2 TABLE ACCESS BY INDEX ROWID TABLE T2 Cost: 1  Bytes: 40  Cardinality: 1   
                                1 INDEX RANGE SCAN INDEX T2_NAME Cost: 1  Cardinality: 1  
                            3 INDEX UNIQUE SCAN INDEX (UNIQUE) T3_ID Cost: 1  Bytes: 17  Cardinality: 1     
                7 INDEX UNIQUE SCAN INDEX (UNIQUE) T1_ID Cost: 1  Bytes: 17  Cardinality: 1                 
            9 INDEX RANGE SCAN INDEX T2_ID_PARENTID Cost: 1  Bytes: 72  Cardinality: 3                      
        15 NESTED LOOPS  Cost: 7  Bytes: 867  Cardinality: 17                       
            13 NESTED LOOPS  Cost: 6  Bytes: 1,292  Cardinality: 38                     
                11 CONNECT BY PUMP                  
                12 INDEX RANGE SCAN INDEX T2_PARENTID_ID Cost: 1  Bytes: 312  Cardinality: 13               
            14 INDEX UNIQUE SCAN INDEX (UNIQUE) T1_ID Cost: 1  Bytes: 17  Cardinality: 1                    

1 个答案:

答案 0 :(得分:0)

您唯一的选择是在t1.id和t2.parentid上创建索引,并确保通过分析执行计划来使用这些索引,如果是这种情况则使用提示。还要注意为t1,t2及其索引提供新的性能统计。