我有两张桌子:
Table_1
[Group No] [Test No] [Description]
123 1 [First Test]
123 2 [Second Test]
123 3 [Third Test]
Table_2
[Sample No] [Test No] [Result Description]
ABC 1 [Some More Result]
ABC 3 [Some Result]
DEF 1 [A Result]
DEF 2 [Results More]
DEF 3 [Bad Results]
这是我的疑问:
SELECT Table_1.[Group No], Table_1.[Test No], Table_1.Description, Table_2.[Result Description]
FROM Table_1
LEFT OUTER JOIN Table_2 ON Table_1.[Test No] = Table_2.[Test No]
WHERE (Table_1.[Group No] = '123') AND (Table_2.[Sample No] = 'ABC')
djacobson的查询:
SELECT Table_1.[Group No], Table_1.[Test No], Table_1.Description, Table_2.[Result Description]
FROM Table_1
LEFT OUTER JOIN Table_2 ON Table_1.[Test No] = Table_2.[Test No]
WHERE (Table_1.[Group No] = '123')
AND (Table_2.[Sample No] IS NULL OR Table_2.[Sample No] = 'ABC')
返回:
[Group No] [Test No] [Description] [Result Description]
123 1 [First Test] [Some More Result]
123 3 [Third Test] [Some Result]
但我真正想要的是:
[Group No] [Test No] [Description] [Result Description]
123 1 [First Test] [Some More Result]
123 2 [Second Test] NULL
123 3 [Third Test] [Some Result]
这可能吗?我想用2号测试返回记录。但是,如何加入不存在的记录?或者这根本不可能?有哪些替代方案?
答案 0 :(得分:43)
尽管正确使用了外连接,但您通过在WHERE子句中包含该表中的列,将结果集限制为表2中存在值的情况。如果您想要样品编号为ABC的记录,或者表2中没有记录,则需要执行以下操作:
SELECT Table_1.[Group No], Table_1.[Test No], Table_1.Description, Table_2.[Result Description]
FROM Table_1
LEFT OUTER JOIN Table_2 ON Table_1.[Test No] = Table_2.[Test No]
WHERE (Table_1.[Group No] = '123')
AND (Table_2.[Sample No] IS NULL OR Table_2.[Sample No] = 'ABC')
或者,您可以在连接到Table_2时过滤Table_2的结果(在这种情况下,读取更干净一点):
SELECT Table_1.[Group No], Table_1.[Test No], Table_1.Description, Table_2.[Result Description]
FROM Table_1
LEFT OUTER JOIN Table_2 ON Table_1.[Test No] = Table_2.[Test No] AND Table_2.[Sample No] = 'ABC'
WHERE (Table_1.[Group No] = '123')
那应该完成同样的事情。这里重要的一点是WHERE子句过滤了连接表的结果。如果您正在使用外连接但希望过滤外连接表,则必须处理连接远端不存在记录的情况。