防止重复一组列

时间:2018-06-26 19:49:49

标签: sql insert-into

CREATE TABLE middle_table (
        id SERIAL PRIMARY KEY NOT NULL,
        col_a_id INTEGER NOT NULL REFERENCES table_b (id),
        col_b_id INTEGER NOT NULL REFERENCES table_b (id)
    );

我想防止col_a_idcol_b_id一起重复,以使它们有效:

INSERT INTO middle_table VALUES (1,2), (1,3), (2,3);

这些插入将无效:

INSERT INTO middle_table VALUES (1,2), (1,2);

有没有做自定义功能的简单方法吗?

1 个答案:

答案 0 :(得分:1)

您将使用唯一约束:

CREATE TABLE middle_table (
    id SERIAL PRIMARY KEY NOT NULL,
    col_a_id INTEGER NOT NULL REFERENCES table_b (id),
    col_b_id INTEGER NOT NULL REFERENCES table_b (id),
    UNIQUE (col_a_id, col_b_id)
);