我有一个表可以将表中的另一个成员称为父表。该父母也可以将另一行称为其父级......依此类推。
id col1 col2 parentID
1 foo bar NULL
2 blah boo 1
3 fob far 2
4 wob lob NULL
我想返回给定ID的链。因此,如果id为3,我将返回第3行,第2行和第1行。如果id为2,我将返回第2行和第1行。如果id为1或4,我将返回该行。
谢谢
答案 0 :(得分:11)
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
结果:
id
---
3
2
1
答案 1 :(得分:1)
你去吧
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
答案 2 :(得分:1)
如果您使用递归CTE,请不要忘记添加
h.parentid <> x.id
加入
JOIN hierarchy h ON h.parentid = x.id)
否则你只会最大递归 - 错误,因为它循环
答案 3 :(得分:-1)
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)