2012-04-05 75 views
3

的父母的名字我有一個表像這樣SQL Server查詢發現孩子

ID Name Mother Father 
1 Sue  NULL NULL 
2 Ed  NULL NULL 
3 Emma 1  2 
4 Jack 1  2 
5 Jane NULL NULL 
6 Bonnie 5  4 
7 Bill 5  4 

,我需要輸出如下

ID Name Mother Father 
3 Emma sue  ed 
4 jack sue  ed 
6 bonnie jane jack 
7 bill jane jack 

我已經試着寫與加盟ňCTE查詢,但想不出來了邏輯,有人可以幫我

回答

4
SELECT t.ID, t.Name, m.Name, f.Name 
FROM your_table t 
INNER JOIN your_table m ON m.ID = t.Mother 
INNER JOIN your_table f ON f.ID = t.Father 

使用LEFT JOIN如果要包括錄音功DS沒有Mother和/或Father節點:

SELECT t.ID, t.Name, ISNULL(m.Name, 'Orphan') Mother, ISNULL(f.Name, 'Orphan') Father 
FROM your_table t 
LEFT JOIN your_table m ON m.ID = t.Mother 
LEFT JOIN your_table f ON f.ID = t.Father 
+0

非常感謝大衛。 。有效 !!! – LOL 2012-04-05 10:45:46

0

嘗試這樣的事:

select 
    p.id, p.name, p1.name as mother, p2.name as father 
from people p 
inner join people p1 on p1.id = p.mother 
inner join people p2 on p2.id = p.father 
-2

選擇查詢

SELECT A.*  
FROM tbl A 
    ,tbl M  
    ,tbl F  
WHERE A.Mother = M.ID  
    AND A.Father = F.ID  

無內加入..

+0

這仍然是一個INNER JOIN – Taryn 2015-05-14 14:40:28

+0

我的意思是說沒有內部加入關鍵字... – 2015-05-14 15:23:05