【问题标题】:Do I need to declare a unique constraint for `bigint generated always as identity`?我是否需要为“始终作为身份生成的 bigint”声明一个唯一约束?
【发布时间】:2021-01-29 16:25:51
【问题描述】:

我正在创建一个多租户应用程序,并将tenant_id 添加到我的租户将访问的所有表中。所有的表也将有一个递增的代理键。我需要声明代理键的唯一约束还是多余的?

CREATE TABLE tenant (
  primary key (tenant_id),
  tenant_id  bigint generated always as identity
);

CREATE TABLE person (
  primary key (tenant_id, person_id)
  person_id  bigint generated always as identity,
  tenant_id  bigint not null,

  unique (person_id),  -- Do I need this?

  foreign key (tenant_id) references tenant
);

【问题讨论】:

  • person_id应该是表person中的主键。
  • 您必须声明约束。虽然“作为身份”似乎表示为键或唯一列,但它没有。它仅表示它仅表示该字段的构建方式以及对其的一些限制。

标签: postgresql primary-key multi-tenant


【解决方案1】:

表的主键应该是唯一标识表行的最小列集。所以应该是person_id,因为它是专门为此目的而创建的。

如果您需要加快基于 tenant_id 的搜索,请在 tenant_id(tenant_id, person_id) 上添加另一个(非唯一)索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2011-04-27
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    相关资源
    最近更新 更多