我有两张桌子:
Table_1
[Group No] [Test No] [Description]
123 1 [First Test]
Table_2
[Sample No] [Test No] [Result Description]
DEF 1 [A Result]
这是我的疑问:
SELECT Table_1.[Group No], Table_1.[Test No], Table_1.Description, Table_2. [Result Description], A.Table_2. [Result Description]
FROM Table_1
LEFT JOIN Table_2 ON Table_1.[Test No] = Table_2.[Test No]
LEFT JOIN Table_2 A ON Table_1.[Test No] = A.Table_2.[Test No]
WHERE Table_1.[Test No] = '1'
AND (Table_2.[Sample No] = 'DEF')
AND (A.Table_2.[Sample No] = 'ABC')
返回:
[Group No] [Test No] [Description] [Result Description]
空行......
但我真正想要的是:
[Group No] [Test No] [Description] [Result Description] [Result Description]
123 1 [First Test] [A Result] NULL
这可能吗?
答案 0 :(得分:2)
以这种方式试试。
SELECT Table_1.[Group No], Table_1.[Test No], Table_1.Description, Table_2. [Result Description], A.Table_2. [Result Description]
FROM Table_1
LEFT JOIN Table_2 ON Table_1.[Test No] = Table_2.[Test No] AND Table_2.[Sample No] = 'DEF'
LEFT JOIN Table_2 A ON Table_1.[Test No] = A.Table_2.[Test No] AND A.Table_2.[Sample No] = 'ABC'
WHERE Table_1.[Test No] = '1'
你这样做的方式需要在table_2中存在一条记录,因为WHERE表示该表中的一列必须等于某事。
答案 1 :(得分:0)
当你离开加入时,你必须小心你在where子句中放置的内容。试试这个:
SELECT Table_1.[Group No], Table_1.[Test No], Table_1.Description, Table_2. [Result Description], A.Table_2. [Result Description]
FROM Table_1
LEFT JOIN Table_2 ON Table_1.[Test No] = Table_2.[Test No]
and (Table_2.[Sample No] = 'DEF')
LEFT JOIN Table_2 A ON Table_1.[Test No] = A.Table_2.[Test No]
AND (A.Table_2.[Sample No] = 'ABC')
WHERE Table_1.[Test No] = '1'
将这些条件放在连接中允许左连接包括左边不满足条件的记录,因为右表上没有符合条件的记录。