我正在尝试构建一个返回与特定商机相关联的联系人列表的查询。
我有3个表:联系人,机会和关系(多对多)
联系人
id name
---------
1 Davey Jones
2 Bob Hope
3 Tiger Woods
4 Hillary Clinton
机会
id description
------------------
1 visit the locker
2 singing and dancing
3 playing golf
4 laughing and crying
关系
id firstid firsttype secondid secondtype
---------------------------------------------------------
1 1 contact 1 opportunity
2 3 opportunity 3 contact
3 4 contact 4 opportunity
4 4 opportunity 3 contact
现在,如果我有opportunity_id,我想返回与该机会相关联的所有联系人。
因此,如果opportunity_id = 4,则成功查询的结果应为:
Hillary CLinton
Tiger Woods
但这是我的查询,只返回1条记录:
SELECT
contacts.name
FROM
contacts
INNER JOIN relationships ON contacts.id = relationships.secondid
INNER JOIN opportunities ON opportunities.id = relationships.firstid
where
opportunities.id=4
and (relationships.firsttype='opportunity' and relationships.secondtype='contact')
or (relationships.firsttype='contact' and relationships.secondtype='opportunity')
我被困在如何在这个查询中触发联接。
编辑:我刚刚发现了UNION,然后尝试了这个,它似乎有效:(select contacts.name from contacts where contacts.id =
(select secondid as id from relationships where (firstid = 4 and (firsttype='opportunity' and secondTtpe='contact' ) ) ) )
UNION
(select contacts.name from contacts where contacts.id =
(select firstid as id from relationships where (secondid = 4 and (firsttype='contact' and secondtype='opportunity' ) ) ) )
但这看起来很笨拙。这是解决这个问题的最好方法吗?
答案 0 :(得分:1)
试试这个:
SELECT contacts.name FROM contacts
inner join (
SELECT * from relationships
where
(firstid = 4 and (firsttype='opportunity' and secondtype='contact' ) )
or
(secondid= 4 and (firsttype='contact' and secondtype='opportunity' ) )
) rel
on contacts.id = rel.id;
答案 1 :(得分:0)
以简单的方式,您需要更改表relationships
的设计,我建议:
<强>关系强>
id id_contact id_opportunity
-------------------------------------
1 1 1
2 3 3
3 4 4
4 3 4
因此,对relationships
的更改,您的查询可能如下所示:
SELECT contacts.name
FROM contacts
INNER JOIN relationships ON contacts.id = relationships.id_contact
INNER JOIN opportunities ON opportunities.id = relationships.id_opportunity
WHERE opportunities.id=4;
您必须记住规范化表格(因此表格relationships
必须具有其他表格中的标识符,每个表格只有一个 ...这就是为什么是标识符),并且在many-to-many
表格中要小心。