如何在一个表上查找父子关系的所有子项

时间:2013-09-09 18:58:27

标签: sql oracle oracle-sqldeveloper

如何在文件夹下找到所有孩子?比如在资源管理器中你有一个文件夹,你有文件夹+文件夹等。

我想找到文件夹2下的所有文件夹

我正在使用ORACLE db。

Folder 1
| |
| Folder 2
| |  |
| |  Folder 3
| |  |  |
| |  |  Folder 7
| |  |  |
| |  |  Folder 8
| |  |
| |  Folder 4
| |
| Folder 5
| |
| Folder 6 
|
Folder 10

此查询为我提供了父级层次结构。

SELECT AL_ITEM_ID, AL_FATHER_ID, AL_DESCRIPTION
FROM ALL_LISTS
CONNECT BY AL_ITEM_ID = PRIOR AL_FATHER_ID
start with AL_DESCRIPTION = 'Folder 7'

1 个答案:

答案 0 :(得分:2)

我认为这会奏效:

Select
    al_item_id, 
    al_father_id,
    al_description
From 
    all_lists
Connect By 
    Prior al_item_id = al_father_id
Start With
    al_description = 'Folder 2'
Where
    Level > 1

如果没有,这几乎肯定会,它取决于在连接之前或之后评估的位置:

Select
    al_item_id,
    al_father_id,
    al_description
From (
    Select
        al_item_id, 
        al_father_id,
        al_description,
        level as lvl
    From 
        all_lists
    Connect By 
        Prior al_item_id = al_father_id
    Start With
        al_description = 'Folder 2'
    ) x
Where
    lvl > 1