Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Retrieve Hierarchial Data

Status
Not open for further replies.

wildsharkuk

Programmer
Mar 12, 2004
36
GB
Hi I have a Hierarchial table with user_id + user_parent_id and would like to know how to retrieve / show only the bottom most child eg

Code:
Dave
  |
  +--Steve
       |
       +--Mark
       |
       +--Paul
            |
            +--Carl

so would need to return Mark and Carl as these are the bottom most children.

any help would be greatly appreciated

thanks

wildsharkuk
 
Assuming that you have got all your people in a single table which is joined to itself on ParentID=PeopleID then a sub-query like this might work:
Code:
Select PersonID From People 
  Where PersonID Not In (Select ParentID From People)
This will pull out all the people who do not appear as parents.

Geoff Franklin
 
Hierarchial table"? What Database are you using? Not Access. Access is a Relational DBMS.
Here's one way your table should look like:
User_ID User Parent_ID
Then you can do a self-join to get who is child of who, or parent of who, etc.
Maybe someone else will accept your table structure and supply another answer.
 
fneily, that's exactly how his table actually looks, it's called a hierarchical table because it stores hierarchical data (in what's called the adjacency model -- "parent_id" is the way this model works)

geoff, your query is close but will work correctly if you add a WHERE clause to your subquery --
Code:
select name 
  from HierarchicalTable
 where user_id not in
   ( select user_parent_id 
       from HierarchicalTable 
      where user_parent_id is not null )

here's another way --
Code:
select name 
  from HierarchicalTable as T
 where not exists
   ( select 1
       from HierarchicalTable 
      where user_parent_id = T.user_id )

r937.com | rudy.ca
 
Apologies for delay, been a meeting all morning.

to all thanks for your rapid response, the code works a treat thankyou very much.

regards

wildsharkuk
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top