I have a table with a structure like (id, parent_id) in Oracle11g.
id parent_id
---------------
1 (null)
2 (null)
3 1
4 3
5 3
6 2
7 2
I’d like to query it to get all the lines that are hierarchically linked to each of these id, so the results should be :
root_id id parent_id
------------------------
1 3 1
1 4 3
1 5 3
2 6 2
2 7 2
3 4 3
3 5 3
I’ve been struggling with the connect by and start with for quite some time now, and all i can get is a fraction of the results i want with queries like :
select connect_by_root(id) root_id, id, parent_id from my-table
start with id=1
connect by prior id = parent_id
I’d like to not use any for loop to get my complete results.
Any Idea ?
Best regards,
Jérôme Lefrère
PS : edited after first answer, noticing me i had forgotten some of the results i want…
The query you posted is missing the
fromclause and left an underscore out ofconnect_by_root, but I’ll assume those aren’t actually the source of your problem.The following query gives you the result you’re looking for:
The central problem is that you were specifying a specific value to start from, rather that specifying a way to identify the root rows. Changing
id = 1toparent_id is nullallows the entire contents of the table to be returned.I also added the outer query to filter the root rows out of the result set, which wasn’t mentioned in your question, but was shown in your desired result.
SQL Fiddle Example
Comment Response:
In the version provided, you do get descendants of
id = 3, but not in such a way that3is the root. This is because we’re starting at the absolute root. Resolving this is easy, just omit thestart withclause:SQL Fiddle Example