【问题标题】:Unique Identifier in multiple schemas多个模式中的唯一标识符
【发布时间】:2016-10-13 12:18:14
【问题描述】:

正如标题所示,我希望有一个唯一的 ID 作为主键,但要跨越多个模式。我知道 UUID,但它太贵了。

有没有办法解决这个问题?

【问题讨论】:

  • 您可以添加具有模式 id 的列并在两列上创建 PK。这种方式 id 将是串行的,但密钥对在模式之间将始终是唯一的

标签: postgresql schema unique primary-key


【解决方案1】:

您可以创建一个全局序列并在表中使用它,而不是 serial 列创建的自动序列。

create schema global;
create schema s1;
create schema s2;

create sequence global.unique_id;

create table s1.t1
(
   id integer default nextval('global.unique_id') primary key
);

create table s2.t1
(
   id integer default nextval('global.unique_id') primary key
);

serial 列的区别在于,序列unique_id 不“知道”它被id 列使用。如果删除了相应的列(或表),而这不是您想要的全局序列,则会自动删除“串行序列”。

但是有一个缺点:您无法确保手动插入这两个表中的重复值。如果您想确保序列始终用于插入值,您可以创建一个始终从序列中获取值的触发器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 2011-08-17
    • 2012-07-18
    相关资源
    最近更新 更多