具有约束中间层的3级嵌套的数据模型

时间:2018-02-06 04:36:17

标签: postgresql database-design

我正在使用Postgres为以下问题寻找合适的数据模型。是否可以不诉诸跨表约束或应用程序级别检查?

以下实体在嵌套的3级层次结构中相关:

  1. 亚群
  2. 项目
  3. 有这3个限制:

    1. 子组属于一个组
    2. 项目与群组是多对多的
    3. 与组关联的项目属于与该组关联的0或1个子组

1 个答案:

答案 0 :(得分:1)

-- Group (GroupID) exists.
group {GroupID}
   PK {GroupID}

-- Sub-group (SubID) belongs to group (GroupID).
subgrp {SubID, GroupID}
    PK {SubID}
    SK {SubID, GroupID}  -- unique, (superkey needed for FK target)
   FK1 {GroupID} REFERENCES group {GroupID}

-- Item (ItemID) exists.
item {ItemID}
  PK {ItemID}

-- Item (ItemID) is associated with group (GroupID).
item_group {ItemID, GroupID}
        PK {ItemID, GroupID}
       FK1 {ItemID}  REFERENCES item  {ItemID}
       FK2 {GroupID} REFERENCES group {GroupID}

-- Item (ItemID) associated with group (GroupID) belongs to sub-group (SubID).
item_subgrp {ItemID, GroupID, SubID}
         PK {ItemID, GroupID}
        FK1 {ItemID, GroupID} REFERENCES item_group {ItemID, GroupID}
        FK2 {SubID, GroupID}  REFERENCES subgrp     {SubID, GroupID}

注意:

All attributes (columns) NOT NULL

PK = Primary Key
SK = Superkey (Unique)
AK = Alternate Key (Unique)
FK = Foreign Key