gpt4 book ai didi

sql - 所有祖先/ parent 和 child 的单一分层查询 (DB2/SQL Server)

转载 作者:行者123 更新时间:2023-12-02 00:00:12 25 4
gpt4 key购买 nike


我找到了 Oracle 在两个分层 CONNECT BY 查询上使用 UNION ALL 的解决方案,一个获取祖先,另一个获取子级。
我希望对 DB2SQL Server 实现相同的效果。
我知道一个元素可能是层次结构中的根、分支或叶子。我需要获取它的整个层次结构。

假设我有itemid='item3'和class='my class',我需要找到它的祖先和 child ,我想出了:

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,我就可以得到祖先。现在,如果我删除评论,它似乎处于无限循环中。一定有办法让它发挥作用。
我能够在层次结构的一个方向(祖先或子级)中获得结果,但我无法在单个查询中获得这两个结果。
有人尝试过类似的事情吗?

谢谢

最佳答案

如果您不介意使用两个 WITH 语句,以下将返回整个层次结构树。

测试数据

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

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

SQL语句

;WITH children AS (
SELECT class
, itemid
, parent
, 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
, i.itemid
, i.parent
, 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

关于sql - 所有祖先/ parent 和 child 的单一分层查询 (DB2/SQL Server),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5733853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com