2009-04-23 55 views
3

我試圖從我的Oracle數據庫中提取動物譜系樹。Oracle中的譜系查詢

這裏的表:

Animal 
------------------------ 
Animal_ID 
Parent_Male_ID 
Parent_Female_ID 
.... 
.... 
------------------------ 

如果我指定的動物,我可以使用這樣的事情讓所有的後代(陽側上):

SELECT * 
FROM animal 
START WITH animal_id = 123 
CONNECT BY PRIOR animal_id = parent_male_id 

我想找到一種方法來擴展它,如果我指定一個動物,它將取得父母雙方,然後取回他們所有的後代。

有什麼想法? (這是Oracle 9.2)

回答

2
SELECT * 
FROM animal 
START WITH 
     animal_id IN 
     (
     SELECT parent_male_id 
     FROM animal 
     WHERE animal_id = 123 
     UNION ALL 
     SELECT parent_female_id 
     FROM animal 
     WHERE animal_id = 123 
     ) 
CONNECT BY 
     PRIOR animal_id IN (parent_male_id, parent_female_id) 

但是,這個查詢會很慢。

最好使用這一個:

SELECT DISTINCT(animal_id) AS animal_id 
FROM (
     SELECT 0 AS gender, animal_id, father AS parent 
     FROM animal 
     UNION ALL 
     SELECT 1, animal_id, mother 
     FROM animal 
     ) 
START WITH 
     animal_id IN 
     (
     SELECT father 
     FROM animal 
     WHERE animal_id = 9500 
     UNION ALL 
     SELECT mother 
     FROM animal 
     WHERE animal_id = 9500 
     ) 
CONNECT BY 
     parent = PRIOR animal_id 
ORDER BY 
     animal_id 

,將使用HASH JOIN和速度要快得多。

參見性能細節在我的博客此項: