我在两个分层 CONNECT BY 查询上使用 UNION ALL 找到了 Oracle 的解决方案,一个获取祖先,另一个获取子查询。
我想为DB2和SQL Server实现相同的目标。
我知道一个元素可能是层次结构上的根、分支或叶。我需要获取它的整个层次结构。
假设我有itemid='item3' 和 class='my class',我需要找到它的祖先和孩子,我想出了:
with ancestor (class, itemid, parent, base, depth)
as (
select root.class, root.itemid, root.parent, root.itemid, 0
from item root
where root.class = 'myclass'
and root.itemid = 'item3'
-- union all
-- select child.class, child.itemid, child.parent, root.base, root.depth+1
-- from ancestor root, item child
-- where child.class = root.class
-- and child.parent = root.itemid
union all
select parent.class, parent.itemid, parent.parent, parent.itemid, root.depth-1
from ancestor root, item parent
where parent.class = root.class
and parent.itemid = root.parent
)
select distinct class, itemid, parent, base, depth
from ancestor
order by class, base, depth asc, itemid
我想要这样的结果:
class itemid parent base depth
myclass item1 null item3 -2
myclass item2 item1 item3 -1
myclass item3 item2 item3 0
myclass item4 item3 item3 1
myclass item5 item5 item3 2
如果上面的 SQL 运行,我得到祖先很好。现在,如果我删除评论,它似乎处于无限循环中。必须有办法让这项工作发挥作用。
我能够在层次结构一个方向(祖先或孩子)中获得结果,但我无法在单个查询中获得两者。
有没有人尝试过这样的事情?
谢谢