连接表关系数据



我需要创建一个表来存储公司中用户的数据。为此,我想使用一个接线表。我发现有两种方法:

变体1:

create table user_company
(
id uuid default uuid_generate_v4() not null primary key,
is_chief boolean not null,
is_worker boolean not null,
is_trainee boolean not null,
user_id uuid references user on delete cascade not null,
company_id uuid references company on delete cascade not null,
)

变体2:

create type enum_users_role as enum ('chief', 'worker', 'trainee');
create table user_company
(
id uuid default uuid_generate_v4() not null primary key,
state enum_users_role not null,
user_id uuid references user on delete cascade not null,
company_id uuid references company on delete cascade not null,
)

在我的情况下,我确信用户只能处于三种状态之一。选择一个比另一个有好处吗?存储可扩展性?

提前感谢您抽出时间!

第二种方法似乎更可取,因为结构隐含地表明了这三种状态不能同时发生。

您应该对(user_id, company_id)有一个唯一的约束——如果您可以使用多列主键,请将其作为主键,并放弃多余的id

最新更新