2

==

我的问题的 SQL 小提琴在这里

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

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 中,一些线圈可以是其他线圈的孩子,而一些线圈可以是平板的孩子。Slabs 只能是 Heats 的子代。热火没有父母。

现在,我想获得线圈 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 子句时,查询变得非常缓慢。如何更有效地实现所需的输出?

4

1 回答 1

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    
于 2012-11-12T05:48:06.590 回答