【问题标题】:Composite primary key vs single primary key and unique index复合主键与单主键和唯一索引
【发布时间】:2014-04-19 21:48:31
【问题描述】:

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

  • 类别
  • 被提名人
  • 阶段

顾名思义,我将在各自的表格中存储类别和被提名者。投票将分为两个阶段。在第一阶段,每个类别将有 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 中的记录多得多。我仍然不确定哪个选项更方便。

SQL Fiddle for option 1

SQL Fiddle for option 2

【问题讨论】:

    标签: mysql composite-primary-key indices primary-key-design


    【解决方案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 字段。您只需将此列作为外键链接到原始列。

    【讨论】:

    • 不要问我 stackoverflow 是如何让我回答一个 2 岁的问题的:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多