【发布时间】:2014-08-28 15:56:42
【问题描述】:
我有以下疑问:
select * from (
select p1.c as child, p1.p as parent, 1 as height
from parent as p1
where (p1.c=3 or p1.c=8);
union
select p2.c as child, p2.c as parent, 2 as height
from parent as p2
where (p1.child=3 or p1.child=8) and p1.parent = p2.child;
)
架构是:
CREATE TABLE parent(p int, c int);
我正在尝试找到从 child 到 root 的路径。 [编辑] 并附加我们必须遍历的边数。
目标是将孩子的父母与其父母联系起来,例如:
(8, 2, 1)
(8, 5, 2) -> 8 is the lowest child, 2 is its parent, and 5 it's 2 parent.
一些样本数据:
10 | 5
10 | 12
12 | 3
12 | 4
4 | 6
4 | 7
5 | 11
5 | 2
2 | 8
如何在将形成p2 的第二个查询中使用第一个查询p1 的引用?
在那之后我应该有;
(8,2,1)
(3,12,1)
(3,10,2)
(8,5,2)
这样我就已经知道该怎么做才能完成我想要的了。
【问题讨论】:
-
如果使用 Oracle,请查找 CONNECT BY,并可能混入一个 LISTAGG。
-
这些例子对我来说很好。第三列是“高度”,即节点之间的距离。第一列是“孩子”,第二列是“父母”(身高 1)或“祖父母”(身高 2)。
-
@spencer7593:现在,那个加起来了。谢谢。
-
您的树是像示例中那样限制为三个级别,还是您正在寻找 n 个级别的通用解决方案?
-
为什么这个问题用 4 个不同的 DBMS 标记?
标签: mysql sql oracle sqlite postgresql