如何从2 CONNECT BY提高SQL查询的速度

时间:2012-10-02 12:36:08

标签: sql oracle plsql

我有3个表:t1,t2,t3。

t1 - 分层表(具有id和parent_id)

t1与t2连接,t2与t3(连接)

连接

输入:t1的一些id

有必要在这些标识符上构建一个树(以收集所有父节点)

然后构建一棵树,将t2和t3粘在一起

还需要恢复其子女的t3name(来自t3)的值为父母的上衣

输出:必须为每个t3name接收分层树

我的SQL请求,但速度非常慢:

Miniexample: http://sqlfiddle.com/#!4/0b607/2

SELECT id, name, t3name FROM 
(SELECT distinct t1.id as id, 
                 t1.parent as parent, 
           t1.name as name, 
           connect_by_root(t3.name) as t3name
    FROM table1 t1
    LEFT OUTER JOIN table2 t2
        ON t1.t2_id = t2.id
    LEFT OUTER JOIN table3 t3
        ON t2.t3_id = t3.id
    START WITH t1.id in (83, 98, 9, 19, 4, 101)
        CONNECT BY PRIOR t1.parent = t1.id)
WHERE t3name IS NOT NULL
START WITH parent = 0
    CONNECT BY PRIOR id = parent and PRIOR t3name = t3name

1 个答案:

答案 0 :(得分:1)

在没有看到执行计划的情况下帮助您调整查询有点困难,但如果我理解您,那么您只需要t3name的值为2个连接。

如果确实如此,那么首先尝试从table1获取分层数据并将结果连接到table2和table3。

试试这样:

SELECT id, name, t3name FROM 
(SELECT distinct t1.id as id, 
                 t1.parent as parent, 
           t1.name as name, 
           t3.name as t3name
    FROM (select tt1.name, tt1.id, tt1.parent, connect_by_root(tt1.t2_id) t2_id
         from table1 tt1 
         START WITH tt1.id in (83, 98, 9, 19, 4, 101)
        CONNECT BY PRIOR tt1.parent = tt1.id) t1
    JOIN table2 t2
        ON t1.t2_id = t2.id
    JOIN table3 t3
        ON t2.t3_id = t3.id
    )
WHERE t3name IS NOT NULL
START WITH parent = 0
    CONNECT BY PRIOR id = parent and PRIOR t3name = t3name; 

我向你的小提琴添加了一些主键(看看我是否可以让它使用索引)并放入两个查询。见here