简体   繁体   English

为什么要在数据透视表中将外键定义为主键?

[英]Why should we define foreign keys as primary keys in pivot table?

Today I faced something, Someone defined foreign keys as primary keys in Pivot Table!今天我遇到了一个问题,有人将外键定义为数据透视表中的主键! Why is that?这是为什么? Does it effect on performance ?它对性能有影响吗? What are the benefits and use cases ?有什么好处和用例? Should we define foreign keys as primary keys in pivot table in order to make them unique ??我们是否应该在数据透视表中将外键定义为主键以使其唯一?

Example of my question:我的问题示例: 在此处输入图片说明

Why should define our many-to-many relationship foreign keys as primary keys ?为什么要将我们的多对多关系外键定义为主键?

This is the proper way to build a junction table, aka bridge table, in a NM relationship.这是在 NM 关系中构建连接表(又名桥接表)的正确方法。

Rationale:理由:

  • each order_id (resp user_id ) should refer to a record in master table orders (resp users ), so you do want a foreign key on each of these columns to enforce data integrity每个order_id (resp user_id ) 都应该引用主表orders (resp users ) 中的一条记录,因此您确实希望这些列中的每一个都有一个外键来强制执行数据完整性

  • each (order_id, user_id) tuple should occur not more than once in the bridge table: this can be enforced by using this columns tuple as a composite primary key, or by setting a unique constraint on it.每个(order_id, user_id)元组在桥接表中不应出现多次:这可以通过将此列元组用作复合主键或对其设置unique约束来强制执行。

Of course, it is also possible to define an indenpendent primary key for the junction table (like an auto-incrementend pk), but that is mostly a matter of taste.当然,也可以为连接表定义一个独立的主键(如自动递增的 pk),但这主要是一个品味问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM