我有一个包含两列的表,Parent并且Child.
我需要获取与父记录关联的所有后代的列表。
Source Table
+----+-----------+
| Parent | Child |
+----+-----------+
| a | b |
| b | c |
| c | d |
| d | e |
| e | f |
| f | x |
+----+-----------+
Expected Result:
+----+-----------+
| Parent | Child |
+----+-----------+
| a | b | // As b is the child of a, all the descendants of b
| a | c | // are also descendants of a.
| a | d |
| a | e |
| a | f |
| a | x |
| b | c | // As c is the child of b, all the descendants of c
| b | d | // are also descendants of b.
| b | e |
| b | f |
| b | x |
| c | d |
| c | e |
| c | f |
| c | x |
| d | e |
| d | f |
| d | x |
| e | f |
| e | x |
| f | x |
+----+-----------+
Run Code Online (Sandbox Code Playgroud)
任何想法如何获取父母的所有后代记录?我尝试过使用 self join ,T1.Child = T2.Parent但逻辑不起作用。
我正在使用不支持子句的Teiid VDBRecursive WITH。
ype*_*eᵀᴹ 20
您需要一个递归 CTE(公用表表达式):
with -- recursive
-- some DBMS (e.g. Postgres) require the word "recursive"
-- some others (Oracle, SQL-Server) require omitting the "recursive"
-- and some (e.g. SQLite) don't bother, i.e. they accept both
descendants
(parent, descendant, lvl)
as
( select parent, child, 1
from source
union all
select d.parent, s.child, d.lvl + 1
from descendants d
join source s
on d.descendant = s.parent
)
select *
from descendants
order by parent, lvl, descendant ;
Run Code Online (Sandbox Code Playgroud)
请参阅SQLfiddle。在level我加入没有必要的。它为您提供父母和后代之间的“距离”(1 是孩子,2 是孙子等)。
相关 Teiid 文档的链接:(recursive) CTEs。
PS:对于甲骨文:
LEVEL 是受限关键字 | 归档时间: |
|
| 查看次数: |
53534 次 |
| 最近记录: |