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!

Querying a Self Referencing Table

Status
Not open for further replies.

TDK2001

Programmer
Oct 30, 2001
18
GB
Hi

I have the following table:-

childid parentid description
---------------------------------------------
1 1 Company 1
2 1 Office 1
3 2 Ground Floor
4 3 Section
5 4 Room 1
6 4 Room 2
7 4 Room 3
8 1 Office 2
9 1 Office 3

If I want the details of childid 6 I would like to return:-
Company 1 - Office 1 - Room 2
or
childid 9 would return
Company 1 - Office 3

How do I write a sql statement to do this?

Regards
Tim
 

Dear ;

What is relation between them i.e. ChildID and ParentID. Actually , I could not understand how you can get

Company 1 - office 1 - Room 2 for ChildID 6.

can you explain it so that we can find out any solution.

I think you will have to use Views to get your result. Please, think in this direction. I have worked on it but unable to get your result b/c I could not understand the link b/w them .

Regards,
Muhammad Essa Mughal
 
ChildID 6 has a parentid of 4 (Room 2) which inturn has a parentid of 3 (section) which inturn has a parentid of 2 (ground floor) which has a parentid of 1 which is the parent of them all.
 
You can use a recursive procedure. Check the following links.


You may want to consider Joe Celko's solution - nested sets. It doesn't rely on recursion but will table redesign.

Terry L. Broadbent - DBA
Computing Links:
faq183-874 contains "Suggestions for Getting Quick and Appropriate Answers" to your questions.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top