我有这张桌子,
Parenttbl
ID Name ParentID
---------------------
1 Mary Null
2 Jane 1
3 Jenny 2
4 Jessa 3
我想创建一个从子节点循环到父节点的查询。例如,如果我给出4号id,它将返回3,2,1,Null(从jessa到mary),直到它发现父id为Null。到目前为止,我有这个问题:
SELECT fc2.ID
FROM Parenttbl as fc1
LEFT JOIN Parenttbl as fc2
ON fc1.ParentID = fc2.ID
WHERE fc1.ID = 6
我打算使用while循环。我怎样才能做到这一点?提前致谢。
答案 0 :(得分:0)
您可以使用WITH Common Table Expressions
WITH Hierarchy AS (
SELECT ID,ParentID
FROM People
WHERE ID = 4
UNION ALL
SELECT p.ID, p.ParentID
FROM People p
JOIN Hierarchy h ON h.ParentID = p.ID
)
SELECT ID FROM Hierarchy
答案 1 :(得分:0)
使用递归查询。像这样:
WITH ParentOf (parentid, name, id, parentlevel)
AS
(
-- Anchor query
SELECT parentid, name, id, 1 as parentLevel
FROM parenttbl
WHERE parenttbl.id = 4
UNION ALL
-- Recursive query
SELECT p.parentid, p.name, p.id, parentlevel +1
FROM parenttbl p
INNER JOIN ParentOf
ON p.Id = ParentOf.parentid
)
-- Statement that executes the CTE
SELECT ParentId, name, id, parentlevel
FROM ParentOf;
答案 2 :(得分:0)
最简单的解决方案是使用Recursive CTE
覆盖任何类型的循环或游标方法
with cte as
(
select * from parenttbl
where id = 4
union all
select p.* from parenttbl p
inner join cte c on p.id <= c.parentid
)
select id, name, parentid from cte
group by id, name, parentid