2014-10-30 101 views
0

我想建立一個查詢返回與特定機會相關的聯繫人列表。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')))) 

但這似乎笨重。這是處理這個問題的最好方法嗎?

+0

我不明白的realtionships。也許如果你使用不同的數字來表示聯繫人和機會...... – Strawberry 2014-10-30 17:08:09

+1

這個關係表是可怕的。爲什麼第一種類型和第二種類型是重要的,他們總是會有聯繫和機會。只需要一個contact_id和一個opportunity_id。 – Andrew 2014-10-31 14:01:16

+0

@Andrew我知道,但它不是我的表,它是在一個開源CRM中。還有其他關係類型,例如賬戶。 – lilbiscuit 2014-10-31 15:00:29

回答

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表中更加小心。

+0

關係不是我的表...我無法更改設計。 – lilbiscuit 2014-10-31 13:20:58

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; 
+0

rel.id從哪裏來? – lilbiscuit 2014-10-31 13:22:15

+0

您的內部SELECT將正確返回所有關係。但是你的外部SELECT返回NULL,因爲rel.id和contacts.id沒有關聯。 – lilbiscuit 2014-10-31 13:29:45

+0

@lilbiscuit'rel'是整個內部選擇的別名(就像是從'關係'創建的新表,但是以您需要的方式創建)...請嘗試一下(我已經嘗試過了) – 2014-10-31 16:01:52