Recursive query for parent child hierarchy. Get descendants from a top node

依然范特西╮ 提交于 2019-12-31 04:26:04

问题


I have a table that stores hierarchy data in parent child format with one top node. Multiple levels, and each parent having multiple children. How can I write a recursive query to select only the parent child rows from a particular node down to the last child?

Example table

Parent|child 
1     |2 
1     |3 
2     |4 
2     |5 
3     |6 
3     |7 
6     |8

How can I retrieve only rows from node 3 and all its descendants?


回答1:


If your DBMS is SQL Server you can accomplish this through Common Table Expressions (CTE) using recursion. I believe this works on all versions 2008R2 and above. The below query will give you all the Parent - Child relationships that are descendants of 3.

CREATE TABLE dbo.ParentChildRel
(
    Parent INT
   ,Child INT
)

INSERT INTO dbo.ParentChildRel
VALUES (1,2)
      ,(1,3)
      ,(2,4)
      ,(2,5)
      ,(3,6)
      ,(3,7)
      ,(6,8)
      ,(7,10)

;WITH Hierarchy AS
    (
        SELECT Parent   
              ,Child
        FROM dbo.ParentChildRel
        WHERE Parent = 3
        UNION ALL
        SELECT rel.Parent
              ,rel.Child
        FROM Hierarchy hier
             INNER JOIN dbo.ParentChildRel rel ON hier.Child = rel.Parent
    )
SELECT *
FROM Hierarchy

Results

Parent  Child
3       6
3       7
7       10
6       8


来源:https://stackoverflow.com/questions/47560559/recursive-query-for-parent-child-hierarchy-get-descendants-from-a-top-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!