左连接没有给出正确的输出

left join not giving correct output

我有 2 个 table

tableA

Accountid   
-----------  
10  
11  
12  

tableB

Accountid   |   Date        |   
--------------------------------------------    
10      |   2016-02-02  |   
11      |   2016-02-02  |   
11      |   2016-02-02  |    
15      |   2016-02-03  |   

我期待像

这样的输出
Accountid   |   ID  |   
------------------------------------    
10      |   10  |   
11      |   11  |   
12      |   NULL    |   

我是运行这个查询

select A.accountid,b.accountid as ID 
from tableA as A 
left join tableB as B on a.accountid=b.accountid 
where b.date between '2016-02-02' and '2016-02-02'

但它给我的输出是,我不确定我哪里出错了

Accountid   |   ID  |   
----------------------------------- 
10      |   10  |   
11      |   11  |   

我正在使用 MSSQL 数据库。

当左联接的右 table 的任何字段出现在 WHERE 子句中时,此联接的行为将类似于 INNER JOIN

要获得预期结果,您的查询应如下所示

select A.accountid,b.accountid as ID 
from tableA as A 
left join tableB as B on a.accountid=b.accountid and 
                         b.date between '2016-02-02' and '2016-02-02'

试试这个:

select A.accountid,b.accountid as ID 
from tableA as A left join tableB as B on a.accountid=b.accountid 
where b.date is null or b.date between '2016-02-02' and '2016-02-02'

原因是,AccountID 12 b.date 实际上是空的(因为表 B 中没有行)。因此,如果您允许查询中的日期为空,您将只会获得该行的结果。

如果 b 不存在 (id = 12) 您的 where 子句 return false 。 如果您想查看 id=12 的行,则必须在 "ON" 子句中包含您的测试(b.date 在“2016-02-02”和“2016-02-02”之间):

   select A.accountid,b.accountid as ID from tableA as A left join tableB as B 
on a.accountid=b.accountid and b.date between '2016-02-02' and '2016-02-02'

原因是因为你的select的WHERE子句是在LEFT JOIN

之后执行的

所以,第一个 sql 服务器将按照您的预期提取数据,第 12-NULL 行,

然后它将被您的 WHERE 子句过滤掉并从输出中删除

您可以按照@JaydipJ 和@RémyBaron 的建议在 JOIN 条件下移动日期过滤器

或以这种方式在 JOIN 之前过滤 tableB:

select A.accountid,b.accountid as ID 
from tableA as A 
left join (
  select * 
  from tableB 
  where b.date between '2016-02-02' and '2016-02-02'
) as B on a.accountid=b.accountid