views:

121

answers:

2

Hello all , Can any one please give me the query to get the child name and his grand fathers name For eg - if i have a table Relationships in the i have childid and fatherid columns so how will i get the grandfather,

i can easily get the father name by using a join but for grandfather i need to do joins 2 times so can any one help me with this

D.Mahesh

+4  A: 

Just add an additional join similar to the one you already have.

 select grandparent.name, child.name
 from Relationships child
 inner join Relationships parent
  on child.parentid = parent.id
 inner join Relationships grandparent
  on parent.parentid = grandparent.id
Oded
Hello Oded,Thanks for your prompt response, i tried and it was exact what i wanted.Thanks once againD.Mahesh
mahesh
A: 

I think its possible with single join as below-

select t2.fatherid as grandfather 
from table1 as t1 
inner join table1 as t2 on t1.fatherid=t2.childid 
where t1.childid='grandson_id';
Sadat
Hello Sadat,Thanks for your response,I tried your query but it is giving me the fathers name only not the grandfathers nameD.Mahesh
mahesh
@Sadat: if you post code, like T-SQL code, **please** use the code button (101 010) on the editor toolbar to format those lines as code - they get nicely formatted and get syntax highlighting as a result and are much better to read!
marc_s
@marc_s: thanks
Sadat