显示连接两个表的where子句中的所有Building ID,其中一个表没有Building_ID列

时间:2016-03-23 16:11:17

标签: sql sql-server join

我有两个表格如下所示。以下查询仅返回两列中具有匹配的业务ID的建筑物。但是我需要在下面的查询中返回包含在Where子句中的所有building_ID。如果Business_Id在Business表中不存在,我仍然需要查询为不在Business表中的业务返回Building_Ids,并且具有类似" Not Exists" for Business。[BusinessName]专栏。

构建表

enter image description here

Select odb.Building.[Building_pk], odb.Business.[Business_pk], Business.[BusinessName]
From odb.Building bld
Left Join odb.Business bus
On bld.[Business_fk] = bus.[Business_pk]
Where bld.[Building_pk] 
IN 
(
1,2,3,4,5,6,7,8,9,10
) Order By bld.[Building_pk] Desc

我需要返回此结果集:enter image description here

1 个答案:

答案 0 :(得分:0)

假设WHERE子句中的列表包含有效建筑物,那么您只需要LEFT JOIN而不是内部连接:

Select bld.Business_fk, odb.Business.[Business_pk],
       Business.[BusinessName]
From odb.Building bld Left Join
     odb.Business bus
     On bld.[Business_fk] = bus.[Business_pk]
Where bld.[Building_pk] IN (1,2,3,4,5,6,7,8,9,10)
Order By bld.Business_fk Desc;