问题描述
我必须看到我是sql的新手。
我有一个看起来像这样的表:
child parent
-------------------
Nancy Bob
Oli Bob
Alice Oli
Mira Alice
现在,我需要一条sql语句,该语句赋予我parent-已经为人所知-及其子代及其子代的子代...等等,给定的是父代名称。
示例我需要Bob
系列。 sql应该返回(Bob,Nancy,Oli,Alice,Mira)
我尝试过:select child from myTable where parent='Bob'
这给了我南希和奥利。
有什么想法吗?
解决方法
您可以使用Oracle的层次查询将其与树级别一起使用:
SELECT CHILD,LEVEL FROM TABLE1
START WITH PARENT = 'Bob'
connect by prior child = parent;
,
这是典型的分层查询。一种标准方法使用递归with
子句:
with cte (child,parent) as (
select child,parent from mytable where parent = 'Bob'
union all
select t.child,t.parent
from mytable t
inner join cte c on c.child = t.parent
)
select child from cte