【问题标题】:how to constrain the uniqueness of two columns while ignoring their ordering in Postgres [duplicate]如何限制两列的唯一性,同时忽略它们在 Postgres 中的顺序 [重复]
【发布时间】:2017-04-06 20:22:58
【问题描述】:

在我的 Postgres 数据库中,我使用两列作为主键,例如

CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    PRIMARY KEY (a, c)
);

我想确保不能添加(c, a)。换句话说,如果 (1, 2) 已经在数据库中,那么 (2, 1) 不能被添加。是否可以添加这样的约束?

【问题讨论】:

    标签: sql database postgresql constraints


    【解决方案1】:

    您可以添加基于回报的唯一索引,EG:

    create unique index so45 on example ((ARRAY[greatest(a,c),least(a,c)]));
    

    示例:

    t=# insert into example select 1,2,3;
    INSERT 0 1
    t=# insert into example select 1,2,1;
    INSERT 0 1
    t=# insert into example select 3,2,1;
    ERROR:  duplicate key value violates unique constraint "so45"
    DETAIL:  Key ((ARRAY[GREATEST(a, c), LEAST(a, c)]))=({3,1}) already exists.
    

    在这种情况下,您不需要 PK 来限制唯一性:

    t=# alter table example drop CONSTRAINT example_pkey ;
    ALTER TABLE
    t=# insert into example select 1,3,3;
    ERROR:  duplicate key value violates unique constraint "so45"
    DETAIL:  Key ((ARRAY[GREATEST(a, c), LEAST(a, c)]))=({3,1}) already exists.
    

    【讨论】:

    • intarray 模块允许将此解决方案推广到任意长度的整数集create extension intarray; create unique index set_ac on example (sort(array[a, c]));
    猜你喜欢
    • 2019-06-24
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2023-02-25
    • 2013-03-21
    相关资源
    最近更新 更多