3

我有一张这样的桌子

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

我试过用 join n cte 写查询,但想不出逻辑,有人可以帮我吗

4

3 回答 3

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如果您想包含没有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
于 2012-04-05T10:38:37.697 回答
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
于 2012-04-05T10:40:48.700 回答
-2

选择查询

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

没有内连接..

于 2015-05-14T09:21:27.373 回答