【问题标题】:MySQL: Is it mandatory to create a `Unique Key` when you have 2 `Primary Keys` in a table?MySQL:当您在表中有 2 个“主键”时,是否必须创建一个“唯一键”?
【发布时间】:2014-12-01 05:07:31
【问题描述】:

请注意以下分步说明。

  1. 我有 2 张桌子,TransactionTransaction_FeeTransactionprimary keyidTransaction,这是一个自动生成的值。 Transaction_Feeprimary keyidTransaction_Fee,这也是一个自动生成的值。

  2. 每个Transaction 都有一个Transaction_Fee,因此idTransactionTransaction_Fee 表中的foreign key

  3. 每个Transaction 只能有一个 Transaction_Fee

现在,我想我需要在Transaction_Fee 表中将idTransactionidTransaction_Fee 都设为primary keys,因为Transaction_FeeTransaction 不能 被复制。 p>

现在我的问题是,既然idTransaction_Fee 将有 2 个primary keys,那么为Transaction_Fee 创建一个Unique Key 是否强制?我问这个问题的原因是在某些情况下,我看到人们在表中有 2 个Primary Keys 时创建Unique Keys。但就我而言,由于 Transaction_Fee 可以使用其自动生成的 ID idTransaction_Fee 轻松识别,因此我认为不需要 Unique Key

但我愿意在继续之前听取专家的建议。

【问题讨论】:

    标签: mysql sql database primary-key unique-key


    【解决方案1】:

    您永远不会在一个表中拥有两个主键,根据定义,您只有 一个

    您的要求似乎是:

    • 事务表中的唯一 ID。
    • 费用表中的唯一 ID。
    • 每笔交易最多收取一笔费用。

    在这种情况下,您要做的是在两个表中为其适当的 ID 创建主键,这将防止这些表中出现重复的 ID。

    那么您需要对Transaction_Fee 表中的idTransaction 列进行唯一约束。这将防止两个费用属于单个交易,因为没有两个费用可以具有相同的交易 ID。

    该列还应该有一个外键约束,引用Transaction(idTransaction),以确保它指向一个有效交易(即没有孤立费用)。

    这仍然允许交易有费用的可能性,并且还有一些方法可以确保关系在两个方向上真正一对一,如果那是什么您想要的(每笔交易只收取一笔费用,而不是零或一)。

    但是,在这种情况下,费用似乎真的是交易本身的属性,应该直接进入交易表。

    【讨论】:

    • 感谢您的回复。我没有明白你的意思。您的意思是在Transaction_Fee 表中将idTransaction 设为Unique Key,而不是将其设为Primary_Key
    • @Sniper,是的,完全正确。您不能在费用表中两个主键。我试图弄清楚答案。
    • 谢谢。 That still allows the possibility of a transaction having no fee and there are also ways to ensure the relationship is truly one-to-one in both directions if that's what you want - 实际上TransactionTransaction_Fee 之间的关系是一对一的。 Transaction_Fee 是使用 After Insert TriggerTransaction 自动生成的
    • @Sniper,如果关系是一对一的,那么你应该考虑我的最后一段。听起来费用是交易的内在属性,在这种情况下,3NF 会建议它放在同一张表中。
    • 所有fee 类型的东西都在不同的唯一表中。例如,当涉及到Transaction 时,它具有客户 ID、参考 ID、评论等,因此我认为将费用类型分开是一个好方法。因为Transaction_Fee不只是一个列表,所以费用分为service_chargeoffice_charge10% usage charge等各种其他费用。所有这些都是Transaction_Fee的一部分
    猜你喜欢
    • 1970-01-01
    • 2011-09-16
    • 2013-04-23
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多