我有一个如下表
MyTable
| ID | PARENT_ID |
-----------------------------
| 20 | null |
| 40 | null |
| 50 | null |
| 70 | 122 |
| 100 | 40 |
| 102 | 4 |
| 126 | 100 |
| 9 | 50 |
| 122 | 40 |
| 123 | 9 |
我要为给定的三个孩子126,70和123选择包括所有孩子和父对象的层次树
预期产量
| ID | PARENT_ID |
-----------------------------
| 126 | 100 |
| 100 | 40 |
| 40 | null |
| 70 | 122 |
| 122 | 40 |
| 123 | 9 |
| 9 | 50 |
| 50 | null |
我尝试过
select ID, PARENT_ID
from MyTable
start with ID=126 //this for example
connect by prior ID=Parent;
答案 0 :(得分:1)
You can do it with hierarchical query using CONNECT BY PRIOR
clause:
select * from MyTable start with id in (126,70,123)
connect by prior parent_id = id;
NOTE: Since you have two nodes with parent_id = 40
, you will get two rows with 40 as ID
and null as parent_id
. If you want to leave only one row, use distinct
clause:
select distinct * from MyTable start with id in (126,70,123)
connect by prior parent_id = id;