2010-04-28 92 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