查询以获取祖父母和孙子女

时间:2020-05-10 12:15:16

标签: sql sql-server

我有一张桌子people

ID   name    surname   mother_id  father_id
--------------------------------------------
1    John    smith     null       null
2    kate    m         null       null
3    philip  smith        2         1
4    dimitr  smith        7         3

我尝试了此查询。

SELECT 
    p.name, P.surname, 
    c.name as 'Mothers name', c.surname as 'Mothers surname',  
    gm.name as 'Grandmother name', gm.surname as 'Grandmother surname'
FROM
    dbo.people AS p
JOIN
    dbo.people AS c ON (c.mother = p.Id)
JOIN
    dbo.people AS gm ON (gm.mother = c.Id)

但是它并没有真正返回我的期望

1 个答案:

答案 0 :(得分:1)

ON子句存在的问题:

select p.name, p.surname, 
       coalesce(pm.name, '') as mothername, coalesce(pm.surname, '') as mothersurname,
       coalesce(pf.name, '') as grandmothername, 
       coalesce(pf.surname, '') as grandmothersurname
from people p left join
     people pm
     on pm.id = p.mother_id left join -- use mother_id from people p
     people pf
     on pf.id = p.father_id; -- use father_id from people p;

这里是db-fiddle