如何用SQL生成同组家庭成员关联组合并支持后续遍历
问题
我有一张包含4列的表,列分别为Group_ID、Contact_ID、F_Name、Relationship。需要生成每个Group_ID对应的家庭组内所有成员的关联组合,原表包含数千条记录及多个家庭组,请问如何编写可支持后续数据遍历的初始SQL语句?
原表示例:
| Group_ID | Contact_ID | F_Name | Relationship |
|---|---|---|---|
| 426281 | 928562 | Jim | Father |
| 426281 | 876931 | Meg | Mother |
| 426281 | 474931 | Tom | Son |
| 426281 | 019321 | Pam | Daughter |
期望输出:
| Contact_ID | Relation_ID |
|---|---|
| 928562 | 876931 (Jim is Husband to Meg) |
| 928562 | 474931 (Jim is Father to Tom) |
| 928562 | 019321 (Jim is Father to Pam) |
| 876931 | 928562 (Meg is Wife to Jim) |
| 876931 | 474931 (Meg is Mother to Tom) |
| 876931 | 019321 (Meg is Mother to Pam) |
| 474931 | 928562 (Tom is Son to Jim) |
| 474931 | 876931 (Tom is Son to Meg) |
| 474931 | 019321 (Tom is Brother to Pam) |
| 019321 | 928562 (Pam is Daughter to Jim) |
| 019321 | 876931 (Pam is Daughter to Meg) |
| 019321 | 474931 (Pam is Sister to Tom) |
解决方案
可以通过自连接结合条件判断实现需求,核心思路是将表与自身按Group_ID关联,生成同一家庭组内的所有成员配对,再通过逻辑映射生成对应的关系描述。以下是可直接使用的SQL语句(假设表名为family_contacts):
SELECT a.Contact_ID, CONCAT( b.Contact_ID, ' (', a.F_Name, ' is ', CASE -- 配偶关系映射 WHEN a.Relationship = 'Father' AND b.Relationship = 'Mother' THEN 'Husband' WHEN a.Relationship = 'Mother' AND b.Relationship = 'Father' THEN 'Wife' -- 父母与子女关系映射 WHEN a.Relationship = 'Father' AND b.Relationship IN ('Son', 'Daughter') THEN 'Father' WHEN a.Relationship = 'Mother' AND b.Relationship IN ('Son', 'Daughter') THEN 'Mother' WHEN a.Relationship IN ('Son', 'Daughter') AND b.Relationship = 'Father' THEN 'Son' WHEN a.Relationship IN ('Son', 'Daughter') AND b.Relationship = 'Mother' THEN 'Daughter' -- 兄弟姐妹关系映射 WHEN a.Relationship = 'Son' AND b.Relationship = 'Daughter' THEN 'Brother' WHEN a.Relationship = 'Daughter' AND b.Relationship = 'Son' THEN 'Sister' WHEN a.Relationship = 'Son' AND b.Relationship = 'Son' THEN 'Brother' WHEN a.Relationship = 'Daughter' AND b.Relationship = 'Daughter' THEN 'Sister' -- 未定义关系可自定义默认值 ELSE '' END, ' to ', b.F_Name, ')' ) AS Relation_ID FROM family_contacts a JOIN family_contacts b ON a.Group_ID = b.Group_ID WHERE a.Contact_ID != b.Contact_ID ORDER BY a.Contact_ID, b.Contact_ID;
逻辑说明
- 自连接:通过
a.Group_ID = b.Group_ID确保只处理同一家庭组内的成员配对。 - 过滤条件:
a.Contact_ID != b.Contact_ID排除成员与自身的无效配对。 - 关系映射:使用
CASE语句根据双方的Relationship字段,生成符合期望的关系描述,覆盖配偶、父母子女、兄弟姐妹三类核心家庭关系。 - 结果格式化:通过
CONCAT函数将关联ID和关系描述拼接成目标格式。
扩展说明
- 如果存在更多关系类型(如祖父、叔叔等),只需在
CASE语句中添加对应的映射条件即可。 - 对于数千条记录,只要为
Group_ID字段建立索引,自连接的性能可满足需求,生成的结果集可直接用于后续数据遍历。
内容的提问来源于stack exchange,提问作者Frisco
相关产品推荐
相关产品推荐

