来自三个表的关系查询

时间:2016-02-24 11:40:26

标签: mysql sql

有三个表| users | family | relation

- >用户表。

|ID|Name|
|1 |max |
|2 |sam |

- >家庭表。

|ID|UserID|FamilyMemberID|RelationID |
|1 |1     |       2       |    1     |
|2 |2     |       1       |     2    |

- >关系表

|ID| Name |
|1 |son   |
|2 |father|

我正在尝试编写一个查询,以了解谁是谁的儿子/父亲。

Plz帮助 感谢

1 个答案:

答案 0 :(得分:1)

我仍然不确定你到底需要什么。如果您要在一行中查找用户的父亲和儿子的名称,您可以尝试这样的事情:

SELECT 
    u.name, 
    (SELECT name FROM user where id = father_relation.family_member_id) as 'Son Of',
    (SELECT name FROM user where id = son_relation.family_member_id) as 'Father Of'
FROM user u
LEFT JOIN family son_relation ON(u.id = son_relation.user_id and son_relation.relation_id = 1)
LEFT JOIN family father_relation ON(u.id = father_relation.user_id and father_relation.relation_id = 2)

输出:

| Name     | Son Of  | Father Of|
---------------------------------
| max      |         | sam      |
| sam      | max     |          |