4

我正在建模一个具有以下实体的投票系统:

  • 类别
  • 被提名人
  • 阶段

顾名思义,我将在各自的表格中存储类别和提名者。投票将分为两个阶段。在第一阶段,每个类别将有 8 名候选人。投票最多的 4 名候选人将进入第二阶段(也是最后阶段)。

到目前为止我有这个结构(简化)

category
    id      PK
    name

nominee
    id      PK
    name

phase
    id      PK
    name

我的问题是如何为投票部分建模。我想我有 2 个选项,但我不确定哪个更好,或者每个选项的优缺点是什么:


选项 1:拥有一个带有复合 3 列主键的 category_nominee 表(我很确定这里的“规范”PK 是由这 3 个字段形成的;不确定性能影响;我使用的是 mysql)

category_nominee
    category_id         PK
    nominee_id          PK
    phase_id            PK

我不喜欢的是,要从投票表中引用 category_nominee,我将不得不再次使用这 3 列,因为我在 category_nominee 中没有单个标识符。因此,在投票表中,我将不得不重复 3 列:

vote
    id
    category_id         FK
    nominee_id          FK 
    phase_id            FK

此外,我不确定 category_id 是否应该指向 category.id 或 category_nominee.category_id (我倾向于后者)


选项 2:在 category_nominee 中创建一个自动递增的 id 列,并使 category_id、nominee_id 和 phase_id 成为复合唯一键。

category_nominee
    id
    category_id         Unique
    nominee_id          Unique
    phase_id            Unique

vote
    id                  PK
    category_nominee_id FK

这将简化对 category_nominee 记录的引用并避免一些重复。我希望投票中的记录比 category_nominee 中的记录多得多。我仍然不确定哪个选项更方便。

选项 1 的 SQL Fiddle

选项 2 的 SQL Fiddle

4

1 回答 1

1

根据我对数据建模的了解,选项 1 是不错的选择。也许这就是外键存在的原因。没见过选项2。

但是在您的选项 1 中, category_nominee 和 vote 是重复的。实现这样的事情:

category
    id      PK
    name

nominee
    id      PK
    name

phase
    id      PK
    name

vote
    (category_id         FK
     nominee_id          FK 
     phase_id            FK) PK
    //others fields required or not

如果您想要所有表中的唯一列名,没有什么可以阻止您重命名 (category_nominee.)category_id 字段。您只需将此列链接到原始列作为外键。

于 2016-11-14T14:16:37.577 回答