空外键列

时间:2019-07-24 15:28:33

标签: sql sql-server database foreign-keys

我有一个具有不同类型用户的数据库。将根据用户类型将用户分配到一个位置。例如,一个部门用户将具有SectorId,而社区用户将具有CommunityId。现在,这意味着部门用户将使用Null作为他/她的CommunityId。解决此问题的最佳方法是什么?

我尝试为不同类型的用户创建不同的表,以摆脱这些空列,但我认为这不是最好的方法。

1 个答案:

答案 0 :(得分:0)

如果您没有太多的列,那么您的方法很好。您可以设置check约束来确保数据完整性。

根据您的描述,我认为逻辑如下:

create table t (
    . . .,
    sectorId int references sectors(sectorId),
    communityId int references communities(communityId),
    check ( ( (case when sectorId is not null then 1 else 0 end) +
              (case when sectorId is not null then 1 else 0 end)
            ) = 1  -- exactly one set
          ),
    check ( type = 'sector' and sectorId is not null or
            type = 'community' and communityId is not null
          )
);

这些约束检查:

  • 这些列引用的是正确的表。
  • 仅设置了id列之一。
  • id列与type列保持一致。