获得 child 的全部 parents

Get all parents for a child

我想检索一个id的parentid,如果那个parentid有一个parent再检索它,依此类推。 层次结构类型 table.

id----parentid
1-----1
5-----1
47894--5
47897--47894

我是 sql 服务器的新手并尝试过,一些查询如:

with name_tree as 
(
   select id, parentid
   from Users
   where id = 47897 -- this is the starting point you want in your recursion
   union all
   select c.id, c.parentid
   from users c
   join name_tree p on p.id = c.parentid  -- this is the recursion
) 
select *
from name_tree;

它只给我一行。 我还想将这些记录插入到临时 table 变量中。 我怎样才能做到这一点。提前致谢。抱歉问了这个简单的问题(虽然不是对我)

试试这个来获取 child

的所有 parents
;with name_tree as 
(
   select id, parentid
   from Users
   where id = 47897 -- this is the starting point you want in your recursion
   union all
   select C.id, C.parentid
   from Users c
   join name_tree p on C.id = P.parentid  -- this is the recursion
   -- Since your parent id is not NULL the recursion will happen continously.
   -- For that we apply the condition C.id<>C.parentid 
    AND C.id<>C.parentid 
) 
-- Here you can insert directly to a temp table without CREATE TABLE synthax
select *
INTO #TEMP
from name_tree
OPTION (MAXRECURSION 0)

SELECT * FROM #TEMP

Click here 查看结果

编辑:

如果你想插入一个 table 变量,你可以这样做:

-- Declare table varialbe
Declare @TABLEVAR table (id int ,parentid int)


;with name_tree as 
(
   select id, parentid
   from #Users
   where id = 47897 -- this is the starting point you want in your recursion
   union all
   select C.id, C.parentid
   from #Users c
   join name_tree p on C.id = P.parentid  -- this is the recursion
   -- Since your parent id is not NULL the recursion will happen continously.
   -- For that we apply the condition C.id<>C.parentid 
    AND C.id<>C.parentid 
) 
-- Here you can insert directly to table variable
INSERT INTO @TABLEVAR
select *
from name_tree
OPTION (MAXRECURSION 0)

SELECT * FROM @TABLEVAR

Click here 查看结果

您的查询正在进行递归,但方向相反。因此,如果您将起点更改为:

where id = 1

那么您将拥有用户 1 和他的所有继任者

您没有提到所需的输出和输入。 不过你可以这样试试,

Declare @t table (id int ,parentid int)
insert into @t
select 1,1 union all
select 5,1 union all
select 47894,5 union all
select 47897,47894 

;With CTE as
(
select * from @t where id=1
union all
Select a.* from @t a inner join cte b
 on b.id=a.parentid and
a.id<>b.id
)
select * from cte