Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 在存储在数据库中的树的一部分中查找从根到叶的所有路径_Sql Server_Tree - Fatal编程技术网

Sql server 在存储在数据库中的树的一部分中查找从根到叶的所有路径

Sql server 在存储在数据库中的树的一部分中查找从根到叶的所有路径,sql-server,tree,Sql Server,Tree,假设存储在数据库(MS SQL Server)中的树具有以下结构 CREATE TABLE Nodes( NodeId int PRIMARY KEY, NodeValue varchar(50)); CREATE TABLE Adjacencies( ParentId int REFERENCES Nodes(NodeId), -- every adjacence is unique for specified child node ChildId int

假设存储在数据库(MS SQL Server)中的树具有以下结构

CREATE TABLE Nodes(
   NodeId int PRIMARY KEY, 
   NodeValue varchar(50));

CREATE TABLE Adjacencies(
   ParentId int REFERENCES Nodes(NodeId), 
   -- every adjacence is unique for specified child node
   ChildId int PRIMARY KEY REFERENCES Nodes(NodeId), 
   Weight int);
现在我们有了一个表Foo,它使用了这个树中的值(具有多对多关系)

现在对于指定的FooId,我们有树节点的子集(在FooNodes表中),我们的任务是从这个子集中找到所有“根叶”路径(这个子集不是必需的,仍然是树,而是子树集)

有没有使用SQL语法实现这一点的最佳方法

例如,路径
{{1,2,3},{1,4},{5,6},{9}
的结果表可以具有如下结构

PathId    NodeId    Level
---------------------------
1         1         1       |
1         2         2       | first path
1         3         3       |
2         1         1           | second path
2         4         2           |
3         5         1                | third path
3         6         2                |
4         9         1                      | fourth path

另外,这个任务在命令式语言中非常明显:我们只需要枚举所有结果子树中的所有“根叶”路径,并合并这些路径集。

有最大深度吗?我们需要检测和处理循环吗?@JonKloske你是说什么样的循环?根据定义,这是一棵没有循环的树。哦,对不起,没有在相邻的ChildId上发现“主键”!消除这种担忧;就是那个关于深度的。如果你知道有一个最大深度(n),你可以用(n)个连接来实现,否则我就不知道你想要什么(当然,这并不是说没有方法!)
PathId    NodeId    Level
---------------------------
1         1         1       |
1         2         2       | first path
1         3         3       |
2         1         1           | second path
2         4         2           |
3         5         1                | third path
3         6         2                |
4         9         1                      | fourth path