我在单个表中有树结构,在另一个表中有项关系。我需要从给定的项目中找出所有的父母。
SELECT Id FROM dbo.Items WHERE Selected = 1
因为我从该查询得到6,9,11,所以我需要返回7,5,2的父项id。
我想我应该使用某种递归CTE,但我不知道从哪里开始。
你可以帮帮我吗?谢谢!dbo.Relationship
Id ParentId
3 6
6 7
8 7
7 2
4 9
9 5
5 2
dbo.Items
Id Selected
2 0
3 0
4 0
5 0
6 1
7 0
8 0
9 1
11 1
答案 0 :(得分:1)
左边加入项目和关系之间的相关ID。
SELECT
Items.Id,
Relationship.ParentId
FROM Items
LEFT JOIN Relationship ON Relationship.Id = Items.Id
我过去曾用过这个来获取所有父ID:
with compParent as
(
select * from Component Where ComponentId = @ComponentId
union all
select Component.* from Component join compParent on Component.ComponentId =
compParent.ContainerParentId
)
select * from compParent;
我用这个来吸引所有孩子:
with compChild as
(
select * from Component where ComponentId = @ParentId
union all
select Component.* from Component join compChild on Component.ContainerParentId = compChild.ComponentId
)
select * from compChild;
您还可以查看已经存在的许多stackOverFlow帖子以获取父级和/或子级。或者简单的谷歌搜索" SQL Server获取父母"
答案 1 :(得分:0)
您想获得所选项目的所有父项吗? 我改为使用临时表。
if object_id('tempdb..#Relationship') is not null drop table #Relationship
create table #Relationship(Id int,ParentId int)
insert into #Relationship(Id,ParentId)
SELECT 3,6 UNION
SELECT 6,7 UNION
SELECT 8,7 UNION
SELECT 7,2 UNION
SELECT 4,9 UNION
SELECT 9,5 UNION
SELECT 5,2
if object_id('tempdb..#items') is not null drop table #items
create table #items(Id int, Selected bit)
insert into #items(Id,Selected)
SELECT 2,0 UNION
SELECT 3,0 UNION
SELECT 4,0 UNION
SELECT 5,0 UNION
SELECT 6,1 UNION
SELECT 7,0 UNION
SELECT 8,0 UNION
SELECT 9,1 UNION
SELECT 11,1
;with cte AS (
SELECT i.ID AS SelectedID,r.ParentId FROM #Items AS i INNER JOIN #Relationship AS r ON i.id=r.id WHERE i.Selected=1
UNION ALL
SELECT cte.SelectedID, r.ParentId FROM #Relationship AS r INNER JOIN CTE ON CTE.ParentId=r.id
)
SELECT * FROM cte ORDER BY cte.SelectedID
它可以给你一些帮助吗?
SelectedID ParentId ----------- ----------- 6 7 6 2 9 5 9 2