![](/img/trans.png)
[英]How to get self-referenced table tree structure, based on parent node in tree?
[英]How to get self-referenced table tree structure, based on any node in tree?
我正在尋找一種方法,可以基於任何節點ID來查詢整個樹結構(包括頂級父級,到末級子級結束),無論如何,都可以基於頂級父級,內部的任何節點或非常底層的子級進行查詢。
即與表:
|--------------|
|ID | ParentID|
|--------------|
|229 | NULL |
|230 | 229 |
|231 | 229 |
|232 | 229 |
|233 | 229 |
| |
|300 | NULL |
|301 | 300 |
|302 | 301 |
|303 | 302 |
|304 | 300 |
----------------
基於查詢229或230或231或232或233 ,結果應始終相同:
229
230
231
232
233
基於查詢300或301或302或303或304 ,結果應始終相同:
300
301
302
303
304
您可以使用遞歸CTE將每個ID分配給其最終父對象。 然后,您可以使用此信息從父級獲取所有ID:
with t as (
select v.*
from (values (229, null), (230, 229), (231, 229), (232, 229), (233, 229),
(300, NULL), (301, 300), (302, 301), (303, 300 )
) v(id, parentid)
),
cte as (
select id as ultimate_parent_id, id as relatedid
from t
where parentid is null
union all
select cte.ultimate_parent_id, t.id
from cte join
t
on cte.relatedid = t.parentid
)
select relatedid
from cte
where ultimate_parent_id = (select ultimate_parent_id
from cte
where relatedid = 231
);
這是db <>小提琴。
您需要的是遞歸公用表表達式(CTE) 。
查詢方法如下:
declare @Table table(ID int, ParentID int)
insert into @Table(ID, ParentID) values
(229, NULL),
(230, 229 ),
(231, 229 ),
(232, 229 ),
(233, 229 ),
(300, NULL),
(301, 300 ),
(302, 301 ),
(303, 300 )
declare @LookingForId int = 300 --229
; with cte as (
select ID from @Table where ID = @LookingForId
union all
select t.ID from @Table t inner join cte on cte.ID = t.ParentID
)
select * from cte
常見的表表達式就像臨時視圖,僅存在於查詢中。 遞歸CTE是在自己體內引用自己的CTE。 您可以使用此技術遍歷表中的父子層次結構。
我認為您需要這樣的東西:
SELECT Id
FROM TableName AS T
WHERE ISNULL(ParentId,Id) IN
(
SELECT ISNULL(ParentId,Id)
FROM TableName WHERE Id=229
)
ORDER BY T.Id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.