顺序左连接表现为内连接

时间:2016-10-10 15:28:00

标签: sql sql-server left-join

我在3个表中有以下数据:

  materials          customers             sales
 -----------        -----------        --------------   
  mtrl comp         cust  comp        mtrl  cust  expqty
    1   2            22    2           1     22     1
    2   2            23    2           2     22     2
    3   2            24    2           3     23     3
    4   2            25    2           4     24     4

我希望产生以下结果:

mtrl  cust  expqty  
 1     22     1  
 2     22     2  
 3     22    null  
 4     22    null

在SQL Server中,我使用以下查询:

select a.mtrl,b.cust,c.expqty from materials a left join customers b on a.comp=b.comp 
left join sales c on c.mtrl=a.mtrl and c.cust=b.cust where b.cust=22

虽然我正在使用左连接,但我放弃了最后两行,我得到的只是:

   mtrl  cust  expqty  
     1     22     1  
     2     22     2  

你能告诉我我做错了什么或者我将如何达到预期的效果?

2 个答案:

答案 0 :(得分:2)

问题不在于顺序连接。问题是where子句。这种情况需要进入on条款:

select m.mtrl, c.cust, s.expqty
from materials m left join
     customers c
     on m.comp = c.comp and c.cust = 22 left join
     sales s
     on s.mtrl = m.mtrl and s.cust = c.cust; 

where子句筛选出NULL值,这是将外连接转换为内连接的原因。请注意,我还修复了表别名,因此它们是表名的缩写。

答案 1 :(得分:1)

您已在b子句中的where表中添加了条件。将它移动到连接条件,如下所示:

select a.mtrl,
       b.cust,
       c.expqty
from materials a 
left join customers b 
    on a.comp=b.comp and b.cust=22
left join sales c 
    on c.mtrl=a.mtrl and c.cust=b.cust
相关问题