SQL Join包含NULL

时间:2018-05-15 22:14:23

标签: sql-server join null

使用SQL Server Management Studio 2016(v 13.0)。

我有两个表,我可以使用两个不同的键来连接,其中的问题是两个PK列中都有混合的NULL:

Table 1          Table 2    

Acct1  App1      Acct2  App2    Product
-----------      ----------------------
1      A         NULL   A       Bed 
2      B         2      B       Sofa
3      C         3      NULL    Bed 
4      D         4      D       Bed 

联接表中的所需结果,仅包括Product = Bed:

的结果
Acct  App  Product
1     A    Bed 
3     C    Bed 
4     D    Bed 

谢谢!

2 个答案:

答案 0 :(得分:3)

虽然我同意@ d219的回答应该是正确的解决方案,但是不同的方法可以使用or中的join,例如:

select Acct1,App1,Product 
from table1 inner join table2
on App1=App2 or Acct1=Acct2 
where Product='Bed'

有关使用or join的讨论,请参阅this post

答案 1 :(得分:1)

一种方法是使用每个键执行两个单独的SELECT语句,然后使用UNION语句,如下所示:

SELECT t1.Acct1, t1.App1, t2.Product
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.Acct1 = t2.Acct2
WHERE t2.Product = 'Bed'

UNION 

SELECT t1.Acct1, t1.App1, t2.Product
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.App1 = t2.App2
WHERE t2.Product = 'Bed'