我想建立一個查詢返回與特定機會相關的聯繫人列表。MySql查詢與反向連接
我有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'))))
但這似乎笨重。這是處理這個問題的最好方法嗎?
我不明白的realtionships。也許如果你使用不同的數字來表示聯繫人和機會...... – Strawberry 2014-10-30 17:08:09
這個關係表是可怕的。爲什麼第一種類型和第二種類型是重要的,他們總是會有聯繫和機會。只需要一個contact_id和一個opportunity_id。 – Andrew 2014-10-31 14:01:16
@Andrew我知道,但它不是我的表,它是在一個開源CRM中。還有其他關係類型,例如賬戶。 – lilbiscuit 2014-10-31 15:00:29