2012-11-12 38 views
2

==如何從Oracle中的多個表中獲取Child-Parent關係?

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篇文章中,有些線圈可能是其他線圈的子線,有些線圈可能是板塊的孩子。平板只能是加熱的孩子。加熱沒有父母。

現在,我想獲得線圈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子句時,查詢會變得非常慢。我如何更有效地達到理想的輸出?

回答

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  
+0

非常感謝您 – Ahmad

+0

我忘了問:如果每個表有主鍵的共同的價值觀?我的意思是:ID = 1的線圈可以存在,而ID = 1的板也可以存在。這將如何影響查詢? – Ahmad

+0

@ AhmadAl-Mutawa您可能會遇到'通過循環連接用戶數據'錯誤 - 在該條件下使用'by by nocycle'執行查詢。測試你的數據查詢,看看它的行爲。 –

相關問題