来自 oracle 中两个不同表的分层查询 sql
Hierarchical query from two different tables in oracle sql
我有一个 table 包含类似这样的数据
TABLE_A
ID PARENT_ID NAME PROJECT_ID
1 abc
2 1 def
3 2 ghi
4 3 jkl 101
5 1 mno
我还有另一个 table,其中包含一些依赖于第一个 table '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;
如果我很了解你的需求,这可能是一种方式:
/* 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_a
和 table_b
的所有数据,然后在分层查询中使用此结果,就好像它是单个 table.
结果:
abc
def
ghi
jkl
prs
tuv
mno
我有一个 table 包含类似这样的数据
TABLE_A
ID PARENT_ID NAME PROJECT_ID
1 abc
2 1 def
3 2 ghi
4 3 jkl 101
5 1 mno
我还有另一个 table,其中包含一些依赖于第一个 table '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;
如果我很了解你的需求,这可能是一种方式:
/* 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_a
和 table_b
的所有数据,然后在分层查询中使用此结果,就好像它是单个 table.
结果:
abc
def
ghi
jkl
prs
tuv
mno