mysql左连接但需要第三个表的值

时间:2013-03-08 19:21:17

标签: mysql left-join

我已经阅读了一百个不同的“如何加入三张桌子”的帖子,但似乎无法让我做我想做的事。它似乎与我在网上找到的例子不同,后者只是两个左连接。

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'

好的,所以我知道我想要将测试组连接到测试中,因为我想要一个结果在'tests'中每个测试名称只有一行,其中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)来限制它,但我在表testgroups中没有访问权限。所以,如果我知道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是(在上面的例子中)27而不在平台表中查找它。如何将其合并到我的查询中?我尝试了很多组合,其中没有一个组合正常。以下是我认为可行的一个例子:

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 个答案:

答案 0 :(得分: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';