SQL 如何获取父项及其所有子项和子项的子项...等等
SQL how to get parent and its all children and children of children... etc
我得看看我是新来的sql。
我有一个 table 看起来像这样:
child parent
-------------------
Nancy Bob
Oli Bob
Alice Oli
Mira Alice
现在我需要 sql 语句,该语句给出父项 - 已知 - 及其子项和其子项的子项...等等,给出的是父项名称。
示例我需要 Bob
的家庭。 sql 应该 return (Bob, Nancy, Oli, Alice, Mira)
我试过这个:select child from myTable where parent='Bob'
这给了我 Nancy 和 Oli。
有什么想法吗?
这是典型的分层查询。一种标准方法使用递归 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
您可以使用 Oracle 分层查询来获得这个连同树的级别:
SELECT CHILD, LEVEL FROM TABLE1
START WITH PARENT = 'Bob'
connect by prior child = parent;
我得看看我是新来的sql。
我有一个 table 看起来像这样:
child parent
-------------------
Nancy Bob
Oli Bob
Alice Oli
Mira Alice
现在我需要 sql 语句,该语句给出父项 - 已知 - 及其子项和其子项的子项...等等,给出的是父项名称。
示例我需要 Bob
的家庭。 sql 应该 return (Bob, Nancy, Oli, Alice, Mira)
我试过这个:select child from myTable where parent='Bob'
这给了我 Nancy 和 Oli。
有什么想法吗?
这是典型的分层查询。一种标准方法使用递归 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
您可以使用 Oracle 分层查询来获得这个连同树的级别:
SELECT CHILD, LEVEL FROM TABLE1
START WITH PARENT = 'Bob'
connect by prior child = parent;