sql server使用外键使用空值连接表

时间:2015-03-04 08:28:41

标签: sql-server join foreign-keys

我有2张桌子,如下所示。 Activity和UOM表之间存在外键关系。

Activity Table
ActivityID    UOMID    ProcessNam
---------------------------------------
1             2         Process1
2             1         Process2
3             null      Process3

UOM Table
UOMId         UOMText
-------------------------
   1           UOM1
   2           UOM2

以下是我得到的查询和结果集

select a.ActivityID, u.UOMID, a.ProcessName, u.UOMText 
from Activity a
left join UOM u on a.UOMID = u.UOMId

ActivityID      UOMID       ProcessName     UOMText
1               2           Process1        UOM2
2               1           Process2        UOM1

是否可以获得如下额外的行;来自活动表,其中UOMID为空

3               null        Process3        null

我尝试更改联接,如下所示;但结果没有改变

left join UOM u on a.UOMID=u.UOMId or (a.UOMID is null or u.UOMId  is
null)

提前致谢

1 个答案:

答案 0 :(得分:0)

select a.ActivityID, u.UOMID, a.ProcessNam, u.UOMText 
from Activity a 
left join UOM u on a.UOMID=u.UOMId

返回

ActivityID  UOMID   ProcessNam  UOMText
1           2       Process1    UOM2
2           1       Process2    UOM1
3           NULL    Process3    NULL

select a.ActivityID, u.UOMID, a.ProcessNam, u.UOMText 
from Activity a 
left outer join UOM u on a.UOMID=u.UOMId where a.UOMId is not null

返回

ActivityID  UOMID   ProcessNam  UOMText
1           2       Process1    UOM2
2           1       Process2    UOM1