我有两个表。我需要连接它们,但我有一个疑问,因为这两个表没有一个共同的列名。
<表类>
id
名称
性别
tbody><<tr>107 天 F 145 Hawbaker M 155 汉斯道明> 202 Blackston M 227 纵纵横道明> 278 Keffer来说 M 305 快活的 M 329 Mozingo F 425 Nolf M 534 沃道明> 586 通 M 618 Dimartino F 747 BeaneM 878 Chatmon F 904 英国国会议事录 F 表类>
两次联接people表,一次联接父表,一次联接子表。然后按子分组,使用条件聚合得到父和母。
select
c.name as child,
max(case when p.gender = 'M' then p.name end) as father,
max(case when p.gender = 'F' then p.name end) as mother
from relations r
join people p on p.id = r.p_id
join people c on c.id = r.c_id
group by c.id, c.name
order by c.name;
为了说明这在没有聚合的情况下也是可以实现的(同时也展示了一种初学者可能更容易想到的方法):
with fathers as
(
select p.name, r.c_id
from relations r
join people p on p.id = r.p_id
where p.gender = 'M'
)
, mothers as
(
select p.name, r.c_id
from relations r
join people p on p.id = r.p_id
where p.gender = 'F'
)
, children as
(
select c.name, c.id as c_id
from people c
where c.id in (select r.c_id from relations r)
)
select
children.name as child,
fathers.name as father,
mothers.name as mother
from children
left join mothers on mothers.c_id = children.c_id
left join fathers on fathers.c_id = children.c_id
order by children.name;
我在这里使用外连接的情况下,一个孩子的母亲或父亲是未知的(即不在关系表中)。
嵌套连接应该工作得很整齐。不需要cte或分组。
- 左连接
relations
… - …内部连接具有性别
F
的 - 再次重复性别
M
- 排除已经有孩子的人
people
select
c.name as child,
father.name as father,
mother.name as mother
from people c
left join relations rm
join people mother on mother.id = rm.p_id and mother.gender = 'F'
on rm.c_id = c.id
left join relations rf
join people father on father.id = rf.p_id and father.gender = 'M'
on rf.c_id = c.id
where c.id not in (
select r.p_id
from relations r
);
,db<的在小提琴