如何实现多个多对多关系?
我的模型中有多个多对多关系,包括客户端、订阅、课程:
- 客户端有零个或多个订阅
- 订阅允许客户端访问一个或多个 课程
我已经有三个表,列出了所有客户、订阅计划和课程。在无需复制大量数据的情况下实现多对多关系的最佳方法是什么?
I have several many to many relations in my model consisting of a client, a subscription, a course:
- A client has zero or more subscriptions
- A subscription allows the client to access one or more
courses
I already have three tables that list all the clients, subscription plans and courses. What would be the best method to implement the many-to-many relations without having to duplicate a lot of data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 4 个表:
PK=主键,FK=外键。
关系如下:
说明:每个订阅专门针对一个客户端,因此两者之间存在 1:n 关系。但同一课程可以被不同的客户通过不同的订阅多次预订,因此课程和订阅之间存在:m关系,这是通过链接表
Subscription_Course
解决的。如果需要,您可以在该模型上添加其他约束,例如,在
Subscription_Course
中的(SubscriptionID, CourseID)
上设置唯一键约束。Use 4 tables:
PK=Primary Key, FK=Foreign Key.
Here are the relations:
Explanation: each subscription is specificially for one client, so there is a 1:n relationship between those two. But the same course can be booked more than once by different clients via different subscriptions, so there is a n:m relationship between courses and subscriptions, which is resolved by a link table
Subscription_Course
.You can add additional constraints on that model if you want, for example, put a unique key constraint on
(SubscriptionID, CourseID)
inSubscription_Course
.注意:
ClientSubscriptionNo
是订阅号每个客户端(1,2,3..);在为客户创建新订阅时可以轻松生成它,您可以决定也可以不决定:
Note:
ClientSubscriptionNo
is a subscription number for each client (1,2,3..); it can be easily generated when creating a new subscription for a client usingYou may or may not decide to:
一张表包含 clientId、subscriptionId,另一张表包含 subscriptionId 和 courseId
One table with clientId, subscriptionId and another table with subscriptionId and courseId
在两个表之间存储多对多的常见方法是将两个表中的键放入第三个表,如下所示
Common approach to store many-to-many between two tables is to put keys from both tables to the third table like this