【问题标题】:MS SQL Server: View with all parents of a child [duplicate]MS SQL Server:查看孩子的所有父母[重复]
【发布时间】:2018-01-24 11:35:46
【问题描述】:

我有以下映射表,其中包含一对父/子 ID:

parent_id | child_id
   3      |     5
   5      |     4
   4      |     9
   6      |     7
   7      |     8

我需要为此表创建一个视图,该视图将列出给定孩子的所有父母。使用上面的示例,结果视图应如下所示:

parent_id | child_id
   3      |     5
   3      |     4
   5      |     4
   3      |     9
   5      |     9
   4      |     9
   6      |     7
   6      |     8
   7      |     8

视图将为特定 id 的每个父级(直接或间接)有一行,父级越多,行越多。可以假设此表中没有循环。

我不知道如何解决这个问题,因为我已经研究了递归选择和循环,但我不确定如何将它们合并到视图中。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您可以使用递归 CTE 来做到这一点:

    with cte as (
          select t.parent_id, t.child_id
          from t
          where t.child_id = @child  -- not needed if you want all
          union all
          select t.parent_id, t.child_id
          from cte join
               t
               on t.child_id = cte.parent_id
        )
    select *
    from cte;
    

    【讨论】:

    • 这给出了正确数量的结果,但遵循上面的示例,例如 9 在结果表中出现 3 次,但每次 parent_id 都是相同的 - 4 这是它的直接父母。
    猜你喜欢
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多