表1:家庭
Id Name Gender
1 Ram M
2 shashank m
3 maya f
4 manu f
5 anu f
6 raj m
表2:Child_parent
Child_id Parent_id
1 2
1 3
4 5
4 6
编写查询以获得以下路径输出
输出:
Child_id Childname father name mother name
1 Ram shashank Maya
4 manu raj anu
答案 0 :(得分:1)
这有点棘手:
select cp.child_id, f.name,
max(case when gender = 'm' then fp.name end) as father_name,
max(case when gender = 'f' then fp.name end) as mother_name
from child_parent cp join
family f
on cp.child_id = f.id join
family fp
on cp.parent_id = fp.id
group by cp.child_id, f.name;