![](/img/trans.png)
[英]How to get self-referenced table tree structure, based on any node in tree?
[英]How to get self-referenced table tree structure, based on parent node in tree?
我正在尋找一種方法,以基於頂級父級的查詢為基礎,查詢整個樹結構(包括頂級父級,結束頂級子級)。
但! 它應該返回:-結構(不止一個元素),-或僅一個元素(頂層結構,如果下面沒有子元素-但在這種情況下,僅當沒有“更高”的情況下) -ParentID為 NULL案件)。
即與表:
|--------------|
|ID | ParentID|
|--------------|
|229 | NULL |
|230 | 229 |
|231 | 229 |
|232 | 229 |
|233 | 229 |
| |
|300 | NULL |
|301 | 300 |
|302 | 301 |
|303 | 302 |
|304 | 300 |
| |
|305 | NULL |
----------------
基於查詢229 ,結果應為:
229
230
231
232
233
基於查詢230或231或232或233 ,結果應該為空 !
基於查詢300 ,結果應為:
300
301
302
303
304
基於查詢301 ,結果應為:
301
302
303
基於查詢302 ,結果應為:
302
303
基於查詢303或304 ,結果應該為空 !
基於查詢305 ,結果應為:
305
根據上一個問題修改我的答案 ,以適應新的要求。 開始遍歷層次結構時,需要在遞歸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, 302 ),
(304, 300 ),
(305, NULL )
declare @LookingForId int = 305
; with cte as (
select ID from @Table t1 where t1.ID = @LookingForId and (t1.ParentID is null or exists (select * from @Table t2 where t2.ParentID = t1.ID))
union all
select t.ID from @Table t inner join cte on cte.ID = t.ParentID
)
select * from cte
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.