如何使用CTE映射父子关系?

时间:2021-07-28 08:41:36

Say I have a table of items representing a tree-like structured data, and I would like to continuously tracing upward until I get to the top node, marked by a parent_id of NULL. What would my MS SQL CTE (common table expression) look like?

假设我有一个项目表,表示树状结构化数据,我想继续跟踪,直到我到达*节点,标记为parent_id为NULL。我的MS SQL CTE(公用表表达式)是什么样的?

For example, if I were to get the path to get to the top from Bender, it would look like

例如,如果我想要从Bender获得顶部的路径,它看起来就像

Comedy

喜剧

Futurama

飞出个未来

Bender

本德尔

Thanks, and here's the sample data:

谢谢,这是示例数据:

DECLARE @t Table(id int, description varchar(50), parent_id int)

INSERT INTO @T 
SELECT 1, 'Comedy', null UNION 
SELECT 2, 'Futurama', 1 UNION
SELECT 3, 'Dr. Zoidberg', 2 UNION 
SELECT 4, 'Bender', 2 UNION
SELECT 5, 'Stand-up', 1 UNION
SELECT 6, 'Unfunny', 5 UNION
SELECT 7, 'Dane Cook', 6

1 个解决方案

#1


4  

it should look like this:

它应该是这样的:

declare @desc varchar(50)
set @desc = 'Bender'

;with Parentage as
(
    select * from @t where description = @desc
    union all

    select t.* 
    from @t t
    inner join Parentage p
        on t.id = p.parent_id
)
select * from Parentage
order by id asc --sorts it root-first 

#1


4  

it should look like this:

它应该是这样的:

declare @desc varchar(50)
set @desc = 'Bender'

;with Parentage as
(
    select * from @t where description = @desc
    union all

    select t.* 
    from @t t
    inner join Parentage p
        on t.id = p.parent_id
)
select * from Parentage
order by id asc --sorts it root-first