【问题标题】:Recursive CTE for parent and child relationship in SQL ServerSQL Server 中父子关系的递归 CTE
【发布时间】:2017-12-27 21:42:26
【问题描述】:

好的,我在网上看到了很多这样的例子,但我无法让它与我的表一起使用。

表:产品
列: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)

谁能帮帮我?

【问题讨论】:

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


    【解决方案1】:

    您可以在 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”。有关此构造的更多信息将澄清您的问题。

    【讨论】:

      【解决方案2】:

      试试这个:

      ;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)
      

      【讨论】:

        猜你喜欢
        • 2014-05-19
        • 1970-01-01
        • 2022-11-14
        • 2018-01-04
        • 1970-01-01
        • 2012-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多