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
I 5としてたchildIDを与えると、のParentIDは、あろう1(出力)
I 9としてたchildIDを与えると、のParentIDはなり7(出力)
すなわち。根のParentIDは0で、クエリがそこに停止する必要があります。
どのようなクエリを解決するには?
助けてくださいます。
解決
私は、あなたが、あなたのPARENT_IDはchild_ofするノードへのごchild_idの名前を変更するべきだと思います。あなたの列の命名は少し混乱している。
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
の [EDIT:より柔軟で将来性の
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
岩ON DISTINCT! : - )
他のヒント
あなたが望むすべてがルートの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を使用する必要があります。
私はあなたが共通テーブル式を使用する必要があり、あなたが再帰クエリをしたいと思います。私はあなたが使用している1、非常に同様の例とのリンクを提供します。
私はここのだと思います解決。これは、いくつかのヶ月前に私を助けてくれます。
指定された子IDに一致する親IDを取得する例を単純には、次のとおりです。
select parentid
from MyTable
where childid = 5
ただし、上記のデータのために、これはレコードを返しません。
所属していません StackOverflow