我的Oracle数据库如下:
DR_ID | DR_PATH | DR_FILE_OR_FOLDER | DR_PARENT_FOLDER_ID
---------------------------------------------------------------
1 | one.txt | File | 0
2 | two | Folder | 0
3 | three.txt | File | 0
4 | four.txt | File | 2
5 | five | Folder | 2
6 | six | Folder | 5
7 | seven.txt | File | 6
该表表示文件夹结构,DR_ID
是带有序列的主键。 DR_PATH
是文件或文件夹名称,DR_FILE_OR_FOLDER
是类型(文件或文件夹),DR_PARENT_FOLDER_ID
代表父ID(DR_ID
)。
我需要创建一个查询,以基于传递的DR_ID
获取文件夹文件的相对路径。
示例:-如果我通过DR_ID
7,则需要将输出作为two\five\six\seven.txt
如何为此要求创建查询?
答案 0 :(得分:3)
这里是一个选择:
SQL> with test (dr_id, dr_path, dr_parent_folder_id) as
2 (select 1, 'one.txt' , 0 from dual union all
3 select 2, 'two' , 0 from dual union all
4 select 3, 'three.txt', 0 from dual union all
5 select 4, 'four.txt' , 2 from dual union all
6 select 5, 'five' , 2 from dual union all
7 select 6, 'six' , 5 from dual union all
8 select 7, 'seven.txt', 6 from dual
9 )
10 select listagg(dr_path, '\') within group (order by level desc) result
11 from test
12 connect by dr_id = prior dr_parent_folder_id
13 start with dr_id = &par_dr_id;
Enter value for par_dr_id: 7
RESULT
--------------------------------------------------------------------------------
two\five\six\seven.txt
SQL> /
Enter value for par_dr_id: 5
RESULT
--------------------------------------------------------------------------------
two\five
SQL>