sql根据子节点查出所有的父节点的

2025-01-21 12:21:52
推荐回答(3个)
回答1:

用函数做,根据你的表结构改:
父节点查询子节点
create function GetChildID(@ParentID int)
returns @t table(ID int)
as
begin
insert into @t select id from table where parent_id = @ParentID
while @@rowcount<>0
begin
insert into @t select a.id from table as a
inner join @t as b
on a.parent_id = b.ID
and not exists(select 1 from @t where ID=a.ID)
end
return
end
go

子节点查询父节点
create function GetParentID(@ChildID int)
returns @t table(PID int)
as
begin
insert into @t select parent_id from table where ID=@ChildID
while @@rowcount<>0
begin
insert into @t select a.parent_id from table as a
inner join @t as b
on a.ID=b.PID
and not exists(select 1 from @t where PID=a.parent_id)
end
return
end
go

回答2:

一个子节点有多个父节点?

回答3:

写个递归查询不就可以了吗