樹型表的查詢我有3個表即是這樣的關係:需要對T-SQL
樹被加入本身使用的ParentId爲外鍵。樹和所有者表通過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
select * from owner
select * from dbo.xrefOwnerTree where treeid = 31459
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
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
您可能想要更改錨定成員,使其不使用't'作爲別名,因爲它已經是CTE的名稱。如果從最終的'SELECT'中刪除'WHERE'子句,你會得到什麼?如果您只是執行CTE的主播成員,您會得到什麼?你可以發佈一小組示例數據來說明問題嗎?請閱讀[this](http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/)瞭解一些關於改善問題的提示。 – HABO
別名已更改。 當我刪除where子句時,它什麼也不給我。 – Gerson