一对多关系:复合主键还是单主键?
One-to-many relationship: composite primary key or single primary key?
我有一个 table person
包含个人信息,我还有另一个 table person_contact
来存储关于那个人的联系信息(type
显示如果它是 phone 记录或电子邮件记录,并且 record
包含实际的 phone 号码或电子邮件地址)。
我设计的模式是这样的:
在 person_contact
中,我声明 pcont_id
和 person_id
为 PK,而 person_id
是引用 person.person_id
的 FK。我需要 PK pcont_id
吗?在一对多关系中,什么时候应该使用单个 PK,什么时候使用复合 PK 更好?
您不需要 person_id
作为 person_contact
table 中主键的一部分。如果两个 table 之间存在一对多关系,pcont_id
应该是主键。
Do I need the PK pcont_id at all?
我建议,它应该在那里并且应该是你的主键 table 假设你可以为一个人设置多个联系人。
如果一个人只能有一个联系人,那么您不需要 table 本身,您可以直接将数据存储在人 table 中。
如果您仍想单独存储它,则不需要 pcont_id
列,您的 person_id
列应标记为主键。
When should I use a single PK in a one-to-many relationship and when
is it better to use composite PK?
当您有 junction table/associative table
映射多对多关系时,使用复合主键。在一对多关系的情况下,您不需要带有外键列的复合主键。
我有一个 table person
包含个人信息,我还有另一个 table person_contact
来存储关于那个人的联系信息(type
显示如果它是 phone 记录或电子邮件记录,并且 record
包含实际的 phone 号码或电子邮件地址)。
我设计的模式是这样的:
在 person_contact
中,我声明 pcont_id
和 person_id
为 PK,而 person_id
是引用 person.person_id
的 FK。我需要 PK pcont_id
吗?在一对多关系中,什么时候应该使用单个 PK,什么时候使用复合 PK 更好?
您不需要 person_id
作为 person_contact
table 中主键的一部分。如果两个 table 之间存在一对多关系,pcont_id
应该是主键。
Do I need the PK pcont_id at all?
我建议,它应该在那里并且应该是你的主键 table 假设你可以为一个人设置多个联系人。
如果一个人只能有一个联系人,那么您不需要 table 本身,您可以直接将数据存储在人 table 中。
如果您仍想单独存储它,则不需要 pcont_id
列,您的 person_id
列应标记为主键。
When should I use a single PK in a one-to-many relationship and when is it better to use composite PK?
当您有 junction table/associative table
映射多对多关系时,使用复合主键。在一对多关系的情况下,您不需要带有外键列的复合主键。