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_id
和col_b_id
一起重复,以使它们有效:
INSERT INTO middle_table VALUES (1,2), (1,3), (2,3);
这些插入将无效:
INSERT INTO middle_table VALUES (1,2), (1,2);
有没有做自定义功能的简单方法吗?
答案 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)
);