2013-03-08 57 views
0

我讀過一百個不同的「如何加入三個表」的帖子,但似乎無法讓我做我想做的事。這與我在網上找到的例子看起來不同,它們只是兩個左連接。mysql左連接,但需要從第三個表的值

tests 
----- 
id 
name 
platformA <<-- boolean, platformA supports test? 
platformB 
platformX 

testgroups <<-- tuple (testid,platid) is unique 
---------- 
testid  <<-- matches 'id' in 'tests' table above 
platid  <<-- matches id in 'platforms' table below 
grouptype 

platforms 
--------- 
id 
name <<-- corresponds to column name 'platform?' in 'tests' 

好了,我知道我要離開加盟testgroups試驗,因爲我想這對每個測試的名字只有一個行「測試」,其中platformA爲1,不管是否有這樣的結果測試組中的一個條目。我無法弄清楚的是如何獲得涉及的平臺表。這裏是我有什麼不工作:

select tests.name, testgroups.grouptype from tests 
left join testgroups on (tests.id = testgroups.testid) 
where tests.platformA = 1; 

這並不是因爲事實testgroups可以有多個testid = 2,每個platid = ??工作。該元組保證是唯一的,但不是其中的任何一列。所以,它爲每個tests.name提供了一個針對每個平臺的行。我需要通過平臺名稱(比如說platformA)來限制它,但是我沒有在表testgroup中訪問該平臺名稱。所以,如果我知道platid,而不是平臺名稱,我能做到這一點,它不工作:

select tests.name, testgroups.grouptype from tests 
left join testgroups on (tests.id = testgroups.testid and testgroups.platid = 27) 
where tests.platformA = 1; 

我知道,我只想要platformA,但我不知道它的ID是(例如上面)沒有在平臺上查看它。我如何將這個結合到我的查詢中?我嘗試了很多組合,其中沒有一個很好。這裏是我認爲可能的工作的一個例子:

select tests.name, testgroups.grouptype from tests, platforms 
left join testgroups on (tests.id = testgroups.testid and platforms.name = 'platformA') 
where tests.platformA = 1; 

這似乎是非法的語法。我也嘗試了多個左連接,這對我不起作用。

我很想得到答案,但也喜歡關於它爲什麼起作用的一些解釋,因爲我現在一直在敲我的頭。

謝謝, 大衛

==== ====更新

我覺得@Marc差不多吧,但它通過在那裏testgroups.platid有數據爲平臺的行限制了我的輸出。

這是我在利用他的答案,給我的完整的查詢嘗試:

select tests.name, testgroups.grouptype from tests 
left join testgroups on (tests.id = testgroups.testid) 
left join platforms on (testgroups.platid = platforms.id) 
where tests.platformA = 1 and (platforms.name = 'platformA' or platforms.id is null); 

回答

1

您有多個連接在一個查詢中,正是因爲你的最後樣品中......除了你不應該加入混合風格。

select tests.name, testgroups.grouptype 
from tests 
left join testgroups on tests.id = testgroups.testid 
left join platforms ON ...... 
where tests.platformA = 1 and platforms.name = 'platformA'; 
+0

那麼,我會給馬克B正確的答案,雖然你應該閱讀我的更新,因爲它是更正確的答案。 – tanager 2013-03-12 22:47:16