在 aa 数据库环境中,顶层的外键很可能是空值,如下所示:
| pid | cid |
|------*------|
| null | 2 |
| 2 | 3 |
| 3 | 4 |
| null | 6 |
| 6 | 7 |
| 7 | 8 |
Run Code Online (Sandbox Code Playgroud)
所以我建议使用类似的东西:
select connect_by_root(t1.cid) as startpoint,
t1.cid as rootnode
from your_table t1
where connect_by_isleaf = 1
start with t1.cid in (8, 4)
connect by prior t1.pid = t1.cid;
Run Code Online (Sandbox Code Playgroud)
select
t1.cid,
connect_by_root(t1.pid) as root
from
your_table t1
left join your_table t2
on t2.cid = t1.pid
where t1.cid in (4, 8)
start with t2.cid is null
connect by t1.pid = prior t1.cid
Run Code Online (Sandbox Code Playgroud)