SQL query for parent-child chain

2019-01-12 04:35发布

I have a single table that can refer to one other member in the table as a parent. That parent could also refer to one other row as its parent...and so on.

id     col1     col2    parentID
1      foo      bar       NULL
2      blah     boo       1
3      fob      far       2
4      wob      lob       NULL

I would like to return the chain given an id. So if the id were 3 I would return row 3, row 2 and row 1. If id was 2 I would return row 2 and row 1. If the id were 1 or 4 I would just return that row.

thank you

4条回答
孤傲高冷的网名
2楼-- · 2019-01-12 04:58

IF you use a recursive CTE, don't forget to add

h.parentid <> x.id

on your join

JOIN hierarchy h ON h.parentid = x.id)

else you will just a The maximum recursion-error since it loops

查看更多
叛逆
3楼-- · 2019-01-12 05:11

Use a recursive CTE:

DECLARE @id INT
    SET @id = 3

;WITH hierarchy AS (
  SELECT t.id, t.parentid
    FROM YOUR_TABLE t
   WHERE t.id = @id
 UNION ALL
 SELECT x.id, x.parentid
   FROM YOUR_TABLE x
   JOIN hierarchy h ON h.parentid = x.id)
SELECT h.id
  FROM hierarchy h

Results:

id
---
3
2
1
查看更多
该账号已被封号
4楼-- · 2019-01-12 05:22

Here you go

SELECT P.cat_id AS parent_cat_id, P.parent_id AS ROOT, P.cat_name AS parent_cat_name, C.parent_id, C.cat_id, C.cat_name FROM categories AS P LEFT OUTER JOIN categories AS C ON C.parent_id=P.cat_id WHERE P.parent_id IS NULL ORDER BY parent_cat_name, cat_name
查看更多
forever°为你锁心
5楼-- · 2019-01-12 05:24
WITH Hierarchy(ChildId, ChildName, Generation, ParentId)
AS
(
    SELECT Id, Name, 0, ParentId
        FROM UserType AS FirtGeneration
        WHERE ParentId IS NULL        
    UNION ALL
    SELECT NextGeneration.Id, NextGeneration.Name, Parent.Generation + 1, Parent.ChildId

        FROM UserType AS NextGeneration
        INNER JOIN Hierarchy AS Parent ON NextGeneration.ParentId = Parent.ChildId    
)
SELECT *
    FROM Hierarchy
    OPTION(MAXRECURSION 32767)
查看更多
登录 后发表回答