两个独特的列(任何订单都是唯一的)postgresql

时间:2015-09-09 18:41:14

标签: sql database postgresql triggers

我有一个表格,它将两个标识符链接在一起。我希望这些是独一无二的,即:

(1, 2)
(1, 3)
(2, 1) <----- invalid, violates 1,2

我尝试了以下内容:

CREATE TABLE identifiers_relationships (
    id serial primary key,
    identifier1_id integer,
    identifier2_id integer,

    check (
        identifier1_id != identifier2_id
    )
);

CREATE OR REPLACE RULE identifiers_relationships_duplicate_rule AS 
    ON INSERT TO identifiers_relationships 
    WHERE EXISTS 
    (
        SELECT * FROM identifiers_relationships WHERE
        /* basically check for (a, b) already existing) */
        (identifier1_id = NEW.identifier1_id AND identifier2_id = NEW.identifier2_id)
        OR
        /* OR check if (b, a) exists */
        (identifier1_id = NEW.identifier2_id AND identifier2_id = NEW.identifier1_id)
    )
    DO NOTHING;

但是它仍然允许我这样做:

db=> select * from identifiers_relationships;
 id | identifier1_id | identifier2_id 
----+----------------+----------------
  1 |              2 |              1
  2 |              1 |              2
(2 rows)

1 个答案:

答案 0 :(得分:0)

您可以通过使第一个标识符少于而不是第二个标识符并对这两个值设置唯一约束来执行此操作:

CREATE TABLE identifiers_relationships (
    id serial primary key,
    identifier1_id integer,
    identifier2_id integer,

    check (identifier1_id < identifier2_id),
    unique (identifier1_id, identifier2_id)
);

如果您想允许平等,可以使用<=