2010-04-28 90 views
0

任何人都可以请给我的查询来获取子名称和他的父亲的名字例如 - 如果我有一个表关系在我有childid和fatherid列所以我将如何得到祖父,sql查询通过自我加入来获取GrandFather名称

我可以很容易地通过使用获得的父亲名字加入,但对于爷爷,我需要做的加入2倍,从而可以在任何一个可以帮助我解决这个

D.Mahesh

回答

4

只需添加一个类似于您已有的连接。

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 
+0

你好俄德, 感谢您的及时回复,我想,这是确切的我想要的。 再次感谢 D.Mahesh – mahesh 2010-04-28 06:17:32

0

我认为它可能与单个连接为如下─

select t2.fatherid as grandfather 
from table1 as t1 
inner join table1 as t2 on t1.fatherid=t2.childid 
where t1.childid='grandson_id'; 
+0

你好萨达特, 感谢您的回复,我想你的查询,但它给我的父亲名字不仅没有祖父的名字 D.Mahesh – mahesh 2010-04-28 06:20:51

+0

@Sadat:如果您发布的代码,如T-SQL代码,**请**使用编辑器工具栏上的代码按钮(101 010)将这些行格式化为代码 - 它们得到很好的格式化,并因此得到语法突出显示,并且更好阅读! – 2010-04-28 07:51:28

+0

@marc_s:谢谢 – Sadat 2010-04-28 08:09:42