【发布时间】:2020-12-19 22:01:48
【问题描述】:
这是在 Oracle SQL 中使用他们的 BI Publisher 数据模型工具
假设你有两张桌子:
hierarchy_table
acct_description_table
在这两个表中你有这些列:
hierarchy_table
+------------+-----------+-------+
| primarykey | parentkey | depth |
+------------+-----------+-------+
acct_description_table
+------------+-------------+
| acct_value | description |
+------------+-------------+
你想用这些数据建立一个像这样的层次结构(省略描述):
+----------------+----------------+----------------+
| acct_depth_0 | acct_depth_1 | acct_depth_2 | . . .
+----------------+----------------+----------------+
| 450000 | 450040 | | . . .
+----------------+----------------+----------------+
| 450000 | 450050 | 450051 | . . .
+----------------+----------------+----------------+
实现这一目标的最佳方法是什么?到目前为止,我有以下 SQL:
select distinct
t1.acct,
t1.desc,
t2.acct,
t2.desc,
t3.acct,
t3.desc,
t4.acct,
t4.desc,
t5.acct,
t5.desc,
t6.acct,
t6.desc
from (select tree.primarykey acct, act.description desc
from hierarchy_table tree, acct_description_table act
where 1=1
and tree.depth = 0
and act.acct_value = tree.primarykey
) t1
left join (select tree.primarykey acct, tree.parentkey parent, act.description desc
from hierarchy_table tree, acct_description_table act
where 1=1
and tree.depth = 1
and act.acct_value = tree.primarykey
) t2
on 1=1 and t1.acct = t2.parent
...
...
...
left join (select tree.primarykey acct, tree.parentkey parent, act.description desc
from hierarchy_table tree, acct_description_table act
where 1=1
and tree.depth = 5
and act.acct_value = tree.primarykey
) t6
on 1=1 and t5.acct = t6.parent
正如您在这样的查询中看到的,我们将执行 5 次不同的 left join 操作来完成表格。我研究了递归以帮助加快此查询。但是,我不确定如何对其进行编码以满足我们对每个深度对应的列的需求。
有没有人做过类似的事情?或者有谁知道我们可以比由 5 个不同的左连接组成的当前查询更快地做到这一点?谢谢!
【问题讨论】:
标签: sql oracle recursion oracle-sqldeveloper hierarchy