Search code examples
sqloracle-databasetreeconnect-by

Joining other tables in oracle tree queries


Given a simple (id, description) table t1, such as

id  description
--  -----------
1   Alice
2   Bob
3   Carol
4   David
5   Erica
6   Fred

And a parent-child relationship table t2, such as

parent  child
------  -----
1       2
1       3
4       5
5       6

Oracle offers a way of traversing this as a tree with some custom syntax extensions:

select parent, child, sys_connect_by_path(child, '/') as "path"
from t2
connect by prior parent = child

The exact syntax is not important, and I've probably made a mistake in the above. The important thing is that the above will produce something that looks like

parent  child  path
------  -----  ----
1       2      /1/2
1       3      /1/3
4       5      /4/5
4       6      /4/5/6
5       6      /5/6

My question is this: is it possible to join another table within the sys_connect_by_path(), such as the t1 table above, to produce something like:

parent  child  path
------  -----  ----
1       2      /Alice/Bob
1       3      /Alice/Carol
... and so on...

Solution

  • In your query, replace T2 with a subquery that joins T1 and T2, and returns parent, child and child description. Then in the sys_connect_by_path function, reference the child description from your subquery.