简体   繁体   English

即使记录不存在,也返回一行

[英]Return rows even if record does not exist 2 filter in one table

I have 2 tables below: 我下面有2张桌子:

Table_1
[Group No] [Test No] [Description]
123        1         [First Test]

Table_2
[Sample No] [Test No] [Result Description]
DEF         1         [A Result]

Here's my query: 这是我的查询:

 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')

This returns: 返回:

[Group No] [Test No] [Description] [Result Description]

Empty rows.... 空行...

But what I really want is: 但是我真正想要的是:

[Group No] [Test No] [Description] [Result Description] [Result Description]
123        1         [First Test]  [A Result]            NULL

Is this possible? 这可能吗?

Try it this way. 尝试这种方式。

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'

The way you did it required a record to exist in table_2 because the WHERE said that a column from that table had to equal something. 您执行此操作的方式要求table_2中存在一条记录,因为WHERE表示该表中的列必须相等。

When you left join you must be careful what you put in the where clause. 当您退出联接时,必须注意在where子句中输入的内容。 Try this: 尝试这个:

 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'

Putting these conditions in the join allows the left join to include records from the left where the condition is not met because no record exists on the right table matching the criteria. 将这些条件放在联接中将允许左联接在不满足条件的情况下从左开始包括记录,因为在右表上不存在符合条件的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM