2013-03-08 63 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