Genealogy query in Oracle

I am trying to get the family tree of animals from my Oracle database.

Here is the table:

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

If I point out the animal, I can get all of its descendants (on the male side) using something like this:

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

I am trying to find a way to extend this so that if I point out the animal, it will take both parents and then take all its descendants.

Any thoughts? (this is Oracle 9.2)

+3
source share
1 answer
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)

This request, however, will be rather slow.

Better use this one:

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

which will use HASH JOINand much faster.

See this blog post for performance details:

+2

Source: https://habr.com/ru/post/1706985/


All Articles