如何获取父给出SQL Server 2005中的孩子
-
12-09-2019 - |
题
我有一个这样的表
childid parentid
------------------------
1 0
2 1
3 2
4 2
5 3
6 4
7 0
8 7
9 8
10 1
如果我给一个childID的作为图5中,parentId的将为1(输出)
如果我给一个childID的如图9所示,parentId的将是7(输出)
即。根parentId的是0并且查询应该停在那里。
如何解决这样的查询?
请帮忙。
解决方案
我觉得你应该重命名child_id到节点,您PARENT_ID到child_of。您的列命名有点混乱
create table stack_overflow
(
node int, child_of int
);
insert into stack_overflow(node, child_of) values
(1,0),
(2,1),
(3,2),
(4,2),
(5,3),
(6,4),
(7,0),
(8,7),
(9,8),
(10,1);
:此适用于任何CTE-能够RDBMS 强>:
with find_parent(parent, child_of, recentness) as
(
select node, child_of, 0
from stack_overflow
where node = 9
union all
select i.node, i.child_of, fp.recentness + 1
from stack_overflow i
join find_parent fp on i.node = fp.child_of
)
select top 1 parent from find_parent
order by recentness desc
输出:
parent
7
<强> [编辑:更加灵活和面向未来] 强>:
with find_parent(node_group, parent, child_of, recentness) as
(
select node, node, child_of, 0
from stack_overflow
where node in (5,9)
union all
select fp.node_group, i.node, i.child_of, fp.recentness + 1
from stack_overflow i
join find_parent fp on i.node = fp.child_of
)
select q.node_group as to_find, parent as found
from find_parent q
join
(
select node_group, max(recentness) as answer
from find_parent
group by node_group
) as ans on q.node_group = ans.node_group and q.recentness = ans.answer
order by to_find
输出:
to_find found
5 1
9 7
如果您使用的 Postgres的下,上述代码可以缩短为:
with recursive find_parent(node_group, parent, child_of, recentness) as
(
select node, node, child_of, 0
from stack_overflow
where node in (5,9)
union all
select fp.node_group, i.node, i.child_of, fp.recentness + 1
from stack_overflow i
join find_parent fp on i.node = fp.child_of
)
select distinct on (node_group) node_group as to_find, parent as found
from find_parent
order by to_find, recentness desc
DISTINCT ON岩石! : - )
其他提示
如果你想要的是根PARENTID,您可以使用此递归函数:
CREATE FUNCTION test_func
(
@ParentID int
)
RETURNS int
AS
BEGIN
DECLARE @result int;
DECLARE @childID int;
SET @childID = (SELECT ChildID FROM YourTable WHERE ParentID = @ParentID)
IF (@childID = 0)
SET @result = @ParentID
ELSE
SET @result = dbo.test_func(@childID)
RETURN @result
END
GO
然后在主查询:
SELECT dbo.test_func(5)
传在5返回1,根据所提供的数据9返回7。如果您需要每PARENTID即达那链,你应该使用一个CTE。
我想你想递归查询,你应该使用公用表表达式。我会给你一个例子非常相似的一个链接,您使用的一个。
我觉得这里是解。这是几个月前帮我。
例如获得匹配给定的子ID的父ID的一个简单的是:
select parentid
from MyTable
where childid = 5
然而,对于上面的数据,这将返回任何记录。
不隶属于 StackOverflow