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,查詢應該停在那裏。
如何解決這樣的查詢?
請幫忙。
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重命名爲node,你的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在岩石上! :-)
我想你想要一個遞歸查詢,你應該使用公用表表達式。我會給你一個與你使用的非常相似的例子的鏈接。
我認爲here是解決方案。它幾個月前幫了我。
例如獲得匹配給定的子ID父ID的一個簡單的是:
select parentid
from MyTable
where childid = 5
然而,對於上述數據,這將返回任何記錄。
如果你想要的是根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。
...您提供的數據中沒有孩子5或9嗎? – 2009-07-09 16:31:34
我不明白你的例子,它們與數據不匹配。 – RedFilter 2009-07-09 16:32:21