需要在T-SQL中查询树类型表

时间:2016-07-27 00:10:22

标签: sql-server tsql

我有3个像这样相关的表:

enter image description here

使用ParentId作为外键将树连接到自身。 Tree和Owner表通过xrefOwnerTree表具有多对多的关系。

我正在尝试编写一个查询/函数,在其中我给它一个树ID,然后它返回一个最接近层次结构(上行)的OwnerId。

这是我到目前为止所做的:

WITH c (TreeId, Parentid, level, BranchName, OwnerId) as 
(
   SELECT t.TreeId, t.Parentid, 0 as level, BranchName, o.OwnerId
   FROM Tree t
   JOIN xrefOwnerTree ot ON t.TreeID = ot.TreeId
   JOIN Owner o ON ot.OwnerId = o.OwnerId
   WHERE Parentid is null

   UNION ALL

   SELECT t2.TreeId, t2.parentid, c.level + 1, t2.BranchName, o2.OwnerId
   FROM Tree t2 
   JOIN xrefOwnerTree ot2 ON t2.TreeID = ot2.TreeId
   JOIN Owner o2 ON ot2.OwnerId = o2.OwnerId
   INNER JOIN c ON c.TreeId = t2.parentid
)
SELECT * FROM t  WHERE t.TreeId = 32800 and t.OwnerId is not NULL

返回0条记录。它应该返回1.

示例数据:

select * from tree where treeid = 32800
union
select * from tree where treeid = 32646
union
select * from tree where treeid = 32645
union
select * from tree where treeid = 32619
union
select * from tree where treeid = 31459
union
select * from tree where treeid = 31458

enter image description here

select * from owner

enter image description here

select * from dbo.xrefOwnerTree where treeid = 31459

enter image description here

WITH c (TreeId, Parentid, level, BranchName, OwnerId) as 
(
   SELECT t.TreeId, t.Parentid, 0 as level, BranchName, o.OwnerId
   FROM Tree t
   JOIN xrefOwnerTree ot ON t.TreeID = ot.TreeId
   JOIN Owner o ON ot.OwnerId = o.OwnerId
   WHERE Parentid is null

   UNION ALL

   SELECT t2.TreeId, t2.parentid, c.level + 1, t2.BranchName, o2.OwnerId
   FROM Tree t2 
   JOIN xrefOwnerTree ot2 ON t2.TreeID = ot2.TreeId
   JOIN Owner o2 ON ot2.OwnerId = o2.OwnerId
   INNER JOIN c ON c.TreeId = t2.parentid
)
SELECT * FROM c

enter image description here

SELECT t.TreeId, t.Parentid, 0 as level, BranchName, o.OwnerId
FROM Tree t
JOIN xrefOwnerTree ot ON t.TreeID = ot.TreeId
JOIN Owner o ON ot.OwnerId = o.OwnerId
WHERE Parentid is null

enter image description here

1 个答案:

答案 0 :(得分:0)

我没有自己的桌子。我建议您一个接一个地查看你的联盟:

先检查一下:

SELECT t.TreeId, t.Parentid, 0 as level, BranchName, o.OwnerId
   FROM Tree t
   JOIN xrefOwnerTree ot ON t.TreeID = ot.TreeId
   JOIN Owner o ON ot.OwnerId = o.OwnerId
   WHERE Parentid = 0

然后第二个......

希望它可以提供帮助。