如何 select sql / oracle 中节点的所有 children 和 parents

how to select all children and parents of a node in sql / oracle

我有一个 table 如下

我的表格

| ID     |  PARENT_ID |
-----------------------------
|   20      | null      |
|   40     | null      |
|   50     | null      |
|   70     | 122       |
|   100    | 40        |
|   102    | 4         |
|   126    | 100       |
|   9     | 50         |
|   122    | 40        |
|   123    | 9         | 

我想要 select 层次结构树,包括所有 children 和 parent,如下所示,对于给定的三个 children 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;

您可以使用 CONNECT BY PRIOR 子句进行分层查询:

select * from MyTable start with id in (126,70,123)
         connect by prior parent_id = id;

注意:由于您有两个 parent_id = 40 的节点,您将得到两行,其中 40 为 ID,null 为 parent_id。如果只想保留一行,请使用 distinct 子句:

select distinct * from MyTable start with id in (126,70,123)
         connect by prior parent_id = id;