2013-04-23 28 views
6

我的數據在表中有2個字段,Id & ParentId。我用這種結構存儲數據(相似的圖像在後面)。我如何獲得從葉到根的所有路徑,包括Id = 6? (結果樣品是後續)在tsql中獲取來自一組行數據(具有特定id)的所有樹

--Data structure is as follow : 
-- 1 
--/
--2 <- 3  9 
-- \ \ /
-- 4 <- 5 7 8 
-- \///
--  6 - - - 
-- / \ 
-- 10 <- 11 
--/
--12 

--Data In Table Is : 
--Id ParentId 
--1  null 
--2  1 
--3  2 
--4  2 
--5  3 
--5  4 
--6  4 
--6  5 
--6  7 
--6  8 
--7  9 
--8  null 
--9  null 
--10 6 
--11 6 
--11 10 
--12 10 

--Result for all trees that include "Id = 6": 
--12 > 10 > 6 > 4 > 2 > 1 
--12 > 10 > 6 > 5 > 4 > 2 > 1 
--12 > 10 > 6 > 5 > 3 > 2 > 1 
--12 > 10 > 6 > 7 > 9 
--12 > 10 > 6 > 8 
--11 > 10 > 6 > 4 > 2 > 1 
--11 > 10 > 6 > 5 > 4 > 2 > 1 
--11 > 10 > 6 > 5 > 3 > 2 > 1 
--11 > 10 > 6 > 7 > 9 
--11 > 10 > 6 > 8 
--11 > 6 > 4 > 2 > 1 
--11 > 6 > 5 > 4 > 2 > 1 
--11 > 6 > 5 > 3 > 2 > 1 
--11 > 6 > 7 > 9 
--11 > 6 > 8 

回答

4

你的表格說4有自己作爲父母,但沒有其他的東西,但你有一行表明12> 10> 6> 5> 4> 2> 1,所以我不能產生相同的結果建立。

我這個sqlfiddle是在這裏:http://sqlfiddle.com/#!6/873b9/3

假設4有2個父我的代碼看起來像這樣(排序可能會有點不同,但它的SQL所以沒關係):

WITH records as 
(
    SELECT 
    leaf.Id 
    ,leaf.ParentId 
    ,case when NOT EXISTS(SELECT * FROM recTest where ParentId = leaf.Id) then 1 else 0 end as isLeaf 
    FROM recTest as leaf 
) 
,hierarchy as 
(
    SELECT Id 
    ,NULL as ParentId 
    ,cast(Id as varchar(100)) as chain 
    ,isLeaf 
    FROM records 
    where ParentId IS NULL 
    UNION ALL 
    SELECT r.Id 
    ,r.ParentId 
    ,cast(cast(r.Id as varchar(100)) + ' > ' + h.chain as varchar(100)) as chain 
    ,r.isLeaf 
    FROM records as r 
    INNER JOIN hierarchy as h 
     ON r.ParentId = h.Id 
) 
SELECT 
h.chain 
FROM hierarchy as h 
WHERE isLeaf = 1 
AND h.chain like '%6%' 
OPTION (MAXRECURSION 0) 
1

對於像this sample table表,檢查此查詢:

with AllPossiblePath as(
SELECT distinct [descendant] leaf 
    ,(
     SELECT cast(f.dirname as nvarchar(64))+'/' 
     FROM filesystem f JOIN tree_path t 
     ON t.ancestor = f.id 
     WHERE t.descendant=t1.descendant for xml path('') 
    ) possiblePath 
    FROM [db1].[dbo].[tree_path] t1 
    where [descendant] not in(
    SELECT TOP 1000 ancestor 
    FROM [db1].[dbo].[tree_path] 
    where ancestor!=[descendant]) 
) 

select * from AllPossiblePath where possiblePath like '%Dir2%' 

希望這有助於!

相關問題