我无法理解如何在不生成大量重复字段的情况下进行多表连接。
假设我有三个表:
- 家庭:身份证、姓名
- 父母:身份证,家庭,姓名
- 孩子:身份证、家庭、姓名
如果我做一个简单的选择:
select family.id, family.name from family
order by family.id;
我得到一个简单的列表:
ID Name
1 Smith
2 Jones
3 Wong
如果我添加一个内部连接:
select family.id, family.name, parent.first_name, parent.last_name
from family
inner join parent
on parent.family = family.id
order by family.id;
我得到一些重复的字段:
ID Name Parent
1 Smith Howard Smith
1 Smith Janet Smith
2 Jones Phil Jones
2 Jones Harriet Jones
3 Wong Billy Wong
3 Wong Rachel Wong
如果我添加另一个内部连接:
select family.id, family.name, parent.first_name, parent.last_name
from family
inner join parent
on parent.family = family.id
inner join child
on child.family = family.id
order by family.id;
我得到更多重复的字段:
ID Name Parent Child
1 Smith Howard Smith Peter Smith
1 Smith Howard Smith Sally Smith
1 Smith Howard Smith Fred Smith
1 Smith Janet Smith Peter Smith
1 Smith Janet Smith Sally Smith
1 Smith Janet Smith Fred Smith
2 Jones Phil Jones Mark Jones
2 Jones Phil Jones Melissa Jones
2 Jones Harriet Jones Mark Jones
2 Jones Harriet Jones Melissa Jones
3 Wong Billy Wong Mary Wong
3 Wong Billy Wong Jennifer Wong
3 Wong Rachel Wong Mary Wong
3 Wong Rachel Wong Jennifer Wong
我更喜欢的是这样的,因为它更具人类可读性:
ID Name Parent Child
1 Smith Howard Smith Peter Smith
Janet Smith Sally Smith
Fred Smith
2 Jones Phil Jones Mark Jones
Harriet Jones Melissa Jones
3 Wong Billy Wong Mary Wong
Rachel Wong Jennifer Wong
我知道内部连接的好处之一是避免通过笛卡尔积呈现过多的信息。但似乎我得到了与多表连接类似的东西。有没有办法如上所示总结每个组,或者这是否需要使用 Python 等脚本语言进行后处理?
谢谢,
- 担