简体   繁体   English

MySQL 具有三个实体的多对多表关系

[英]MySQL many-to-many table relationship with three entities

Three record tables:三个记录表:

accounts, users and roles帐户、用户和角色

Users can belong to multiple accounts with different roles.用户可以属于具有不同角色的多个帐户。

Currently, I have a join table:目前,我有一个连接表:

accounts_users_roles (With three columns for FK relationships to each tables PK.) accounts_users_roles(具有三列用于每个表 PK 的 FK 关系。)

Primary key in this table is (accounts.id,users.id,roles.id)此表中的主键是 (accounts.id,users.id,roles.id)

Is there a more efficient way to establish these relationships?是否有更有效的方式来建立这些关系?

EDIT: Roles and users may be shared by accounts.编辑:角色和用户可以由帐户共享。 Accounts assign user roles.帐户分配用户角色。

From the comments, I understand the business rules to be that a user has many roles for many accounts.从评论中,我了解到业务规则是用户对多个帐户具有多个角色。 Joe is the manager for the ConHugeCo account, and also does customer service for EvilInc. Joe 是 ConHugeCo 帐户的经理,同时也为 EvilInc 提供客户服务。 Kathy is president of the Hair Club and is also a client.凯西是美发俱乐部的总裁,也是客户。

Yes, a single table is appropriate.是的,一个表是合适的。

account     user     role
ConHugeCo   Joe      Manager
EvilInc     Joe      CustomerService
HairClub    Kathy    President
HairClub    Kathy    Client

create table accounts_roles_users (
  account_id integer not null references accounts(id) on delete cascade,
  role_id integer not null references roles(id) on delete cascade,
  user_id integer not null references users(id) on delete cascade,

  unique(account_id, role_id, user_id)
);

on delete cascade ensures when a user or account or role is deleted, their join table entry is deleted.on delete cascade确保当用户或帐户或角色被删除时,它们的连接表条目也被删除。 And we avoid duplicate entries by making the user/account/role combination unique .我们通过使用户/帐户/角色组合成为唯一来避免重复条目。

You may wish to allow the user_id to be null to indicate an unfilled role.您可能希望允许 user_id 为 null 以指示未填充的角色。

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

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