如何从Oracle中的多个表中获取子 - 父关系?

时间:2012-11-12 05:07:29

标签: sql oracle

==

SQL Fiddle of My Question Here

我有以下与钢铁厂相关的表格

HEATS /* Contains data about raw iron melted from scrap and ores */
SLABS /* Contains data about the output of the first table HEATS */
COILS /* Contains data about the output of SLABS */

通过删除与问题

无关的不必要字段,我简化了上表的结构
create table heats
  ( id number,
    production_date date, 
    heat_name varchar(10),
    parent number
  );

create table slabs
  ( id number,
    production_date date, 
    slab_name varchar(10),
    parent number
  );


create table coils
  ( id number,
    production_date date, 
    coil_name varchar(10),
    parent number
  );

我还插入了一些虚拟数据(但有适当的关系),如下所示:

insert into heats values (1,'01-Nov-2012','GRADE A',null);  
insert into heats values (2,'01-Nov-2012','GRADE B',null);  
insert into heats values (3,'01-Nov-2012','GRADE C',null);  

insert into slabs values (10,'02-Nov-2012','SLAB A',1);
insert into slabs values (20,'02-Nov-2012','SLAB B',2);
insert into slabs values (30,'02-Nov-2012','SLAB C',3);

insert into coils values (100,'03-Nov-2012','COIL A.1',10);
insert into coils values (200,'03-Nov-2012','COIL B.1',20);
insert into coils values (300,'03-Nov-2012','COIL C.1',30);

insert into coils values (400,'03-Nov-2012','COIL A.2',100);
insert into coils values (500,'03-Nov-2012','COIL B.2',200);
insert into coils values (600,'03-Nov-2012','COIL C.2',300);

insert into coils values (700,'03-Nov-2012','COIL A.3',400);
insert into coils values (800,'03-Nov-2012','COIL B.3',500);
insert into coils values (900,'03-Nov-2012','COIL C.3',600);

注意在最近的9个INSERTS中,一些线圈可以是其他线圈的子线,而一些线圈可以是板块的子线。平板只能是热身的孩子。加热没有父母。

现在,我想获得线圈COIL A.3的族谱。我可以简单地获得线圈和线圈之间的子母关系。像这样

select coil_name from coils c
start with coil_name='COIL A.3'
connect by prior c.parent = c.id

工作正常,我得到了输出

COIL A.3
COIL A.2
COIL A.1

但我希望输出还包括来自其他表格(加热和平板)的父母

COIL A.3
COIL A.2
COIL A.1
SLAB A
HEAT A

但是当我尝试将其他表名添加到查询中并修改connect by子句时,查询会变得非常缓慢。如何更有效地实现所需的输出?

1 个答案:

答案 0 :(得分:2)

Union all个查询结果集:

 SQL> select *
  2    from
  3  (
  4    select id
  5         , slab_name as name
  6         , parent
  7      from slabs c
  8  
  9    union all
 10  
 11    select id
 12         , coil_name
 13         , parent
 14      from coils c
 15  
 16    union all
 17  
 18    select id
 19         , heat_name
 20         , parent
 21      from  heats
 22  
 23  
 24    )
 25   start with name='COIL A.3'
 26   connect by prior parent = id
 27  ;

        ID NAME           PARENT
---------- ---------- ----------
       700 COIL A.3          400
       400 COIL A.2          100
       100 COIL A.1           10
        10 SLAB A              1
         1 GRADE A