SQL CTE - >通过从锚到所有行传递值

时间:2017-04-12 15:05:52

标签: sql common-table-expression

我有一个cte,只是循环通过子/父关系链接到自己的表。我有一个种子查询,我想从种子查询中携带一个值到它的所有后代,以便所有行知道它来自哪个种子。有什么办法吗?

WITH   cte
AS     (select Me, MyParent, Attribute 
        from MyTable
        where 
        Attribute in
            (
            847
            ,1011
            ,1019
            )
        UNION ALL
        SELECT Link.Me, Link.Parent, Link.Attribute
        FROM   cte
            JOIN LINK ON cte.Me = S.Parent          
       )

2 个答案:

答案 0 :(得分:1)

WITH   cte 
AS     (
    select Me, MyParent, Attribute, Attribute RootAttr
    from MyTable
    where 
    Attribute in
        (
        847
        ,1011
        ,1019
        )
    UNION ALL
    SELECT Link.Me, Link.Parent, Link.Attribute, cte.RootAttr
    FROM   cte
        JOIN LINK ON cte.Me = S.Parent          
)

评论后编辑:

@article_zone = @driver.find_element(:id, "nbviewer-zone-overlay-13B27E79C7BC32F1").attribute("id")

答案 1 :(得分:0)

这是一个适用于SQL Server的递归CTE示例 您基本上将值从cte传递到cte中的第二个查询 它被称为递归,因为cte调用自身,这使得它循环遍历所有父节点,直到没有父节点可以链接为止。

-- using a table variable, cos it's a demonstration
declare @MyTable table (Child int, Parent int, Attribute int);

insert into @MyTable (Child, Parent, Attribute) values 
(1,2,847),
(1,3,847),
(2,0,1011),
(3,4,1019),
(4,0,1019);

WITH CTE
AS (
    -- the seed records, where the cte starts
    select 
    Child, Parent, Attribute, 
    Child as RootChild, Attribute as RootAttribute, 0 as PreviousChild, 0 as Level
    from @MyTable
    where Attribute in (847, 1011, 1019)

    union all

    -- the records linked to the previously new records in the CTE
    SELECT 
    link.Child, link.Parent, link.Attribute,
    -- we also take fields from the cte to get the previous data that was put in the resultset of the cte
    cte.RootChild, cte.RootAttribute, cte.Child as PreviousChild, cte.Level + 1 as Level
    FROM cte
    JOIN @MyTable link ON (cte.Parent = link.Child)
)
select * from cte 
order by RootChild, Level;

-- This time we link to the link.Parent which will give different results
WITH CTE
AS (
    select 
    Parent, Child, Attribute, 
    Parent as RootParent, Attribute as RootAttribute, 0 as PreviousParent, 0 as Level
    from @MyTable
    where Attribute in (847, 1011, 1019)

    union all

    SELECT 
    link.Parent, link.Child, link.Attribute,
    cte.RootParent, cte.RootAttribute, cte.Parent as PreviousParent, cte.Level + 1 as Level
    FROM cte
    JOIN @MyTable link ON (cte.Child = link.Parent)
)
select * from cte 
order by RootParent, Level;