1

我有 3 张桌子:t1、t2、t3。

t1 - 分层表(有 id 和 parent_id)

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

输入:一些 t1 的 id

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

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

还需要恢复其孩子的 t3name(来自 t3)的价值,以用于父母顶部

输出:需要为每个 t3name 接收分层树

我的 SQL 请求,但它很慢:

小例子: 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
4

1 回答 1

1

在不查看执行计划的情况下帮助您调整查询有点困难,但是如果我理解正确,那么您只需为t3name.

如果确实如此,那么首先尝试从 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; 

我在你的小提琴中添加了一些主键(看看我是否可以让它使用索引)并放置两个查询。看这里

于 2012-10-03T13:22:37.847 回答