来自oracle sql中两个不同表的分层查询

时间:2017-02-22 06:53:45

标签: sql oracle hierarchical

我有一个包含类似这样的数据的表

TABLE_A

ID      PARENT_ID     NAME     PROJECT_ID
1                     abc      
2       1             def      
3       2             ghi
4       3             jkl      101
5       1             mno

我有另一个表,其中包含一些依赖于第一个表的项目' project_id' :

TABLE_B
ID      PROJECT_ID    NAME
1       101           prs
2       101           tuv
3       102           xyz      
4       102           hgf

我想要一个像这样的结果;

abc
def
ghi
jkl
prs
tuv
mno

我尝试过这样的事情,但我不知道如何连接' TABLE_B'

SELECT LEVEL, A.NAME
 FROM TABLE_A A
 CONNECT BY PRIOR A.ID = PRIOR A.PARENT_ID
 ORDER BY LEVEL;

1 个答案:

答案 0 :(得分:2)

如果我理解你的需要,这可能是一种方式:

/* building a test case */
with TABLE_A(ID, PARENT_ID, NAME, PROJECT_ID) as (
    select 1,       null,          'abc',      null from dual union all
    select 2,       1   ,          'def',      null from dual union all
    select 3,       2   ,          'ghi',      null from dual union all
    select 4,       3   ,          'jkl',      101  from dual union all
    select 5,       1   ,          'mno',      null from dual
),TABLE_B(ID, PROJECT_ID, NAME) as (
    select 1,       101,           'prs' from dual union all
    select 2,       101,           'tuv' from dual union all
    select 3,       102,           'xyz' from dual union all
    select 4,       102,           'hgf' from dual
)
/* the query */
select name
from (
        select ID, PARENT_ID, NAME, PROJECT_ID
        from table_a
        UNION ALL
        select a.ID, a.PARENT_ID, b.NAME, a.PROJECT_ID
        from table_b b
              inner join table_a a
                on a.project_id = b.project_id
     )
start with parent_id is null
connect by prior id = parent_id

这里的想法是构建一个包含来自table_atable_b的所有数据的部分结果,然后在分层查询中使用此结果,就好像它是一个表一样。

结果:

abc
def
ghi
jkl
prs
tuv
mno