gpt4 book ai didi

sql - 在 SQL 中查找顶级父级

转载 作者:行者123 更新时间:2023-12-02 03:27:10 25 4
gpt4 key购买 nike

我有两个表如下

  Id   Name
1 A
2 B
3 C
4 D
5 E

RelationHierarchy

ParentId   ChildId
2 1
3 2
4 3

这将形成一个树状结构

          D
|
C
|
B
|
A

ParentId和ChildId是Person表的Id列的外键

我需要编写可以获取顶级父级(即根)的 SQL。任何人都可以建议任何可以帮助我完成此任务的 SQL

最佳答案

您可以使用recursive CTE实现这一目标:

DECLARE @childID INT 
SET @childID = 1 --chield to search

;WITH RCTE AS
(
SELECT *, 1 AS Lvl FROM RelationHierarchy
WHERE ChildID = @childID

UNION ALL

SELECT rh.*, Lvl+1 AS Lvl FROM dbo.RelationHierarchy rh
INNER JOIN RCTE rc ON rh.CHildId = rc.ParentId
)
SELECT TOP 1 id, Name
FROM RCTE r
inner JOIN dbo.Person p ON p.id = r.ParentId
ORDER BY lvl DESC

<强> SQLFiddle DEMO

编辑 - 针对所有 child 的顶级家长的更新请求:

;WITH RCTE AS
(
SELECT ParentId, ChildId, 1 AS Lvl FROM RelationHierarchy

UNION ALL

SELECT rh.ParentId, rc.ChildId, Lvl+1 AS Lvl
FROM dbo.RelationHierarchy rh
INNER JOIN RCTE rc ON rh.ChildId = rc.ParentId
)
,CTE_RN AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY r.ChildID ORDER BY r.Lvl DESC) RN
FROM RCTE r

)
SELECT r.ChildId, pc.Name AS ChildName, r.ParentId, pp.Name AS ParentName
FROM CTE_RN r
INNER JOIN dbo.Person pp ON pp.id = r.ParentId
INNER JOIN dbo.Person pc ON pc.id = r.ChildId
WHERE RN =1

<强> SQLFiddle DEMO

EDIT2 - 让所有人在最后稍微改变一下 JOINS:

SELECT pc.Id AS ChildID, pc.Name AS ChildName, r.ParentId, pp.Name AS ParentName
FROM dbo.Person pc
LEFT JOIN CTE_RN r ON pc.id = r.CHildId AND RN =1
LEFT JOIN dbo.Person pp ON pp.id = r.ParentId

SQLFiddle DEMo

关于sql - 在 SQL 中查找顶级父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17676944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com