繁体   English   中英

空外键列

[英]Null foreign key columns

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

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

如果您没有太多的列,那么您的方法很好。 您可以设置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列协调一致。

我通过添加2个表(Location和LocationType)解决了它。 因此,每个用户都有一个LocationId。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM