MYSQL查询根据查询结果从同一个表中的2个不同记录中提取数据

时间:2015-05-08 18:27:49

标签: mysql join mapping modeling relationships

有关背景信息,请查看此处:

Database Model to Represent Families, Households, and Relationships

基本上,我试图在人与家之间建立关系,而不将关系和家庭与一个家庭户主联系起来。到目前为止,我认为我的模型运作良好。这有什么作用:

SELECT person.person_id,person.first_name, relationship.person_id_a, relationship.person_id_b, relationship.relationship_cd
FROM person, relationship
WHERE person_id = 1
AND (person.person_id = relationship.person_id_a
OR person.person_id = relationship.person_id_b)
AND relationship.relationship_cd <> 0;

结果:

"person_id" "first_name" "person_id_a" "person_id_b" "relationship_cd"
"1" "Joe"   "1" "2" "8 - Spouse"
"1" "Joe"   "1" "3" "7 - Sibling"

所以我知道乔(第1人)有配偶(第2人)和兄弟(第3人)。有没有办法让我使用附加乔与输出关系的人的姓名(或其他信息)?也就是说,查询1告诉我Joe与谁有关系(来自与关系表的连接),我可以嵌套另一个查询,然后我可以拉出该人的名称(从联接回到另一个记录)人表)?所以它看起来像这样:

"person_id" "first_name" "person_id_b" "relationship_cd" "related_person_name"
"1" "Joe" "2" "8 - Spouse" "Susan"
"1" "Joe" "3" "7 - Sibling" "Bob"

1 个答案:

答案 0 :(得分:1)

我会从relationship中选择person_id_a或person_id_b等于您的人的身份证(Joe),然后为person中的a和b人加入relationship两次。例如:

SELECT 
r.person_id_a, 
a.first_name as first_name_a,
r.person_id_b,
b.first_name as first_name_b
r.relationship_cd 
FROM relationship r
JOIN person a on a.person_id = r.person_id_a
JOIN person b on b.person_id = r.person_id_b
WHERE r.person_id_a = 1
OR r.person_id_b = 1 
AND relationship.relationship_cd <> 0;

此查询将返回person_id = 1的人与person_a和person_b名字的所有关系。

如果您希望在答案中获得表单中的结果,则查询可能如下所示:

    SELECT 
        p.person_id,
        case when p.person_id = r.person_id_a then a.first_name else b.first_name end as first_name,
        case when p.person_id = r.person_id_a then b.person_id else a.person_id end as person_id_related,
        case when p.person_id = r.person_id_a then b.first_name else a.first_name end as first_name_related,
        r.relationship_cd 
FROM person p
JOIN relationship r ON r.person_id_a = p.person_id OR r.person_id_b = p.person_id
JOIN person a on a.person_id = r.person_id_a
JOIN person b on b.person_id = r.person_id_b
WHERE p.person_id = 1 
        AND relationship.relationship_cd <> 0;