比方说,我与此类似(驱动器C:上的文件夹层次结构)。
我想获取给定文件夹的顶层文件夹(在这种情况下,我选择的是'1'
),而不是光盘本身,我该怎么做?
层次结构可以有不同的层次。
with data as
(
select '1' name, 'folder' type, 'docs' parent from dual union
select '2' name, 'folder' type, 'docs' parent from dual union
select '3' name, 'folder' type, 'docs' parent from dual union
select 'docs' name, 'folder' type, 'MyFolder' parent from dual union
select 'MyFolder' name, 'folder' type, 'C:\' parent from dual union
select 'C:\' name, 'Drive' type, null parent from dual
)
select name, level from data
start with name = '1'
connect by prior parent = name
order by level;
预期的输出:'Myfolder'
,因为它没有任何其他文件夹作为父文件夹。
答案 0 :(得分:1)
这里是一个选择:
SQL> with data as
2 (
3 select '1' name , 'folder' type, 'docs' parent from dual union
4 select '2' name , 'folder' type, 'docs' parent from dual union
5 select '3' name , 'folder' type, 'docs' parent from dual union
6 select 'docs' name , 'folder' type, 'MyFolder' parent from dual union
7 select 'MyFolder' name, 'folder' type, 'C:\' parent from dual union
8 select 'C:\' name , 'Drive' type, null parent from dual
9 ),
10 inter as
11 (select name, level lvl, type
12 from data
13 start with name = '1'
14 connect by prior parent = name
15 )
16 select name
17 from inter
18 where lvl = (select max(lvl) from inter
19 where type = 'folder');
NAME
--------
MyFolder
SQL>
答案 1 :(得分:1)
请尝试以下操作
WITH data
AS (SELECT '1' name, 'folder' TYPE, 'docs' parent FROM DUAL
UNION
SELECT '2' name, 'folder' TYPE, 'docs' parent FROM DUAL
UNION
SELECT '3' name, 'folder' TYPE, 'docs' parent FROM DUAL
UNION
SELECT 'docs' name, 'folder' TYPE, 'MyFolder' parent FROM DUAL
UNION
SELECT 'MyFolder' name, 'folder' TYPE, 'C:\' parent FROM DUAL
UNION
SELECT 'C:\' name, 'Drive' TYPE, NULL parent FROM DUAL)
SELECT name
FROM data
WHERE parent = (SELECT name
FROM data
WHERE TYPE = 'Drive')
START WITH name = '1'
CONNECT BY PRIOR parent = name
输出
NAME
--------
MyFolder
使用真实数据进行测试,并让我们知道结果。