所有祖先/父项和子项的单一层次查询(DB2 / SQLServer)

我在两个分层的CONNECT BY查询中找到了使用UNION ALL的Oracle解决方案,一个获取祖先,另一个获取子项.
我想为DB2和SQL Server实现相同的功能.
我知道它可以是层次结构上的根,分支或叶子的一个元素.我需要获取整个层次结构.

假设我有itemid =’item3’和class =’我的班级’,我需要找到它的祖先和孩子,我想出来:

with ancestor (class,itemid,parent,base,depth)
as (
    select root.class,root.itemid,root.parent,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,root.depth-1
    from ancestor root,item parent
    where parent.class = root.class
    and parent.itemid = root.parent
)
select distinct class,depth
from ancestor 
order by class,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运行我得到祖先的好.现在,如果我删除评论,它似乎是一个无限循环.必须有办法使这项工作.
我可以在层次结构的一个方向(祖先或孩子)中得到结果,但是我无法在单个查询中获得两者.
有没有人试过这样的东西?

谢谢

解决方法

如果您不介意使用两个WITH语句执行此操作,则以下命令将返回整个层次结构树.

测试数据

DECLARE @item TABLE (
  class VARCHAR(32),itemid VARCHAR(32),parent VARCHAR(32)
)

INSERT INTO @item VALUES 
  ('myclass','item1',null),('myclass','item2','item1'),'item3','item2'),'item4','item3'),'item5','item4')

SQL语句

;WITH children AS (
  SELECT  class,base = itemid,depth = 0
  FROM    @item
  WHERE   class = 'myclass'
          AND itemid = 'item3'          
  UNION ALL
  SELECT  children.class,i.itemid,i.parent,children.base,children.depth + 1
  FROM    children
          INNER JOIN @item i ON i.parent = children.itemid
                                AND i.class = children.class
),parents AS (
  SELECT  *
  FROM    children
  WHERE   depth = 0
  UNION ALL
  SELECT  parents.class,parents.base,parents.depth - 1
  FROM    parents
          INNER JOIN @item i ON i.itemid = parents.parent
                                AND i.class = parents.class                                  
)
SELECT  *
FROM    children
UNION 
SELECT  *
FROM    parents
ORDER BY depth

相关文章

什么是设计模式一套被反复使用、多数人知晓的、经过分类编目...
单一职责原则定义(Single Responsibility Principle,SRP)...
动态代理和CGLib代理分不清吗,看看这篇文章,写的非常好,强...
适配器模式将一个类的接口转换成客户期望的另一个接口,使得...
策略模式定义了一系列算法族,并封装在类中,它们之间可以互...
设计模式讲的是如何编写可扩展、可维护、可读的高质量代码,...