如何遍历与自身有关系的表? [英] How to traverse through a table which has relation to itself?

查看:23
本文介绍了如何遍历与自身有关系的表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张像下面这样的表格

I have a table like the following

Node_Id     Node_Name     Parent_Node_Id
-------     ---------     --------------
1           Root          0
2           Node1         1
3           Node2         1
4           Node3         2
5           Node4         2
6           Node5         5
7           Node6         5
8           Node7         7

表的每一行都有一个父行,由Parent_Node_Id"表示,每行/节点可以是任意数量行/节点的父级.

Each row of the table has a parent row which is indicated by the "Parent_Node_Id" and each row/node can be parent of any number of row/nodes.

我如何编写一个查询,该查询将为我提供具有共享同一父节点的父节点的所有节点的列表?Parent_Node_Id 将作为参数传递.例如,如果 Parent_Node_Id 传递为 2,则查询将返回以下内容 -

How can I write a query which will give me the list of all nodes who have a parent node who all share the same parent node? The Parent_Node_Id will be passed as the parameter. For example, if Parent_Node_Id is passed as 2, the query will return the following -

Node_Id     Node_Name     Parent_Node_Id
-------     ---------     --------------
4           Node3         2
5           Node4         2
6           Node5         5
7           Node6         5
8           Node7         7

推荐答案

;WITH CTE AS (
    SELECT Node_Id,Node_Name, Parent_Node_Id 
    FROM @a WHERE Parent_Node_Id = 2
    UNION ALL
    SELECT c.Node_Id,c.Node_Name, c.Parent_Node_Id 
    FROM @a c
    INNER JOIN CTE p ON p.Node_Id = c.Parent_Node_Id
)
Select * from CTE

示例数据

Declare @a Table( Node_Id int,    Node_Name varchar(100),     Parent_Node_Id int)
insert into @a 

select 1,'Root',0 
UNION SELECT 2,'Node1',1
UNION SELECT 3,'Node2',1
UNION SELECT 4,'Node3',2
UNION SELECT 5,'Node4',2
UNION SELECT 6,'Node5',5
UNION SELECT 7,'Node6',5
UNION SELECT 8,'Node7',7

这篇关于如何遍历与自身有关系的表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆