SQL Server中父子关系的递归CTE

时间:2017-12-27 21:42:27

标签: sql sql-server recursion common-table-expression

好的,所以我在网上看到了很多这样的例子,但我不能用它来处理我的桌子。

表:产品
列:parent_product_id,child_product_id

如果parent_product_id = child_product_id,则parent_product_id没有父级。

child_product_id可以是另一条记录的父级。

我试图这样做,但是我看到了parent_product_id的层次结构= 392193

;with  parents
        as ( 
            select  child_product_id,
                    parent_product_id
            from    product
            where   parent_product_id = child_product_id
            union all 
            select  e.child_product_id,
                    e.parent_product_id
            from    product e
            inner join parents m
            on      e.parent_product_id = m.child_product_id)
  select  *
  from    parents  
  where parents.parent_product_id = 392193
  option (maxrecursion 0)

任何人都可以帮我一把吗?

2 个答案:

答案 0 :(得分:2)

您可以在CTE中移动开始条件:

; with  parents as
        ( 
        select  child_product_id
        ,       parent_product_id
        from    product
        where   child_product_id = 392193
                and parent_product_id = 392193
        union all 
        select  e.child_product_id
        ,       e.parent_product_id
        from    parents m
        join    product e
        on      e.parent_product_id = m.child_product_id
        )
select  *
from    parents  
option  (maxrecursion 0)

(parent_product_id, child_product_id)上的索引会有所帮助。

通常,子记录是指其父记录的主键。在你的情况下,有一些不寻常的事情,父母有一个“child_product_id”。关于此结构的更多信息将澄清您的问题。

答案 1 :(得分:0)

试试这个:

;with  parents
        as ( 
            select  parent_product_id,
                    child_product_id      
            from    product
            where   parent_product_id = child_product_id
            union all 
            select  m.parent_product_id, --this should be parent of top level
                    e.child_product_id   
            from    product e
            inner join parents m
            on      e.parent_product_id = m.child_product_id WHERE e.parent_product_id != e.child_product_id
            )
  select  *
  from    parents  
  where parents.parent_product_id = 392193
  option (maxrecursion 0)