4

我有一个表,我用它以一对多的关系将另外两个表链接在一起。

TableA
id
name

TableB
id
name

LinkTable
TableA_id
TableB_id

基本上,一个 TableA 可以有多个 TableB。非常简单。我现在遇到的问题是创建一个遵循这种关系规则的约束:

LinkTable
TableA_id    TableB_id
1            1
1            2
1            3
2            1
2            2
2            3

我想创建一个唯一约束,将两列组合在一起作为唯一值。所以在上面的链接表中,有了这个新的约束,我可以

INSERT INTO LinkTable (TableA_id, TableB_id) VALUES (1, 4);
INSERT INTO LinkTable (TableA_id, TableB_id) VALUES (1, 5);
INSERT INTO LinkTable (TableA_id, TableB_id) VALUES (2, 6);
INSERT INTO LinkTable (TableA_id, TableB_id) VALUES (3, 1);

With out any problems

And if I try to insert:

INSERT INTO LinkTable (TableA_id, TableB_id) VALUES (1, 1);
INSERT INTO LinkTable (TableA_id, TableB_id) VALUES (1, 3);

约束将触发,因为已经有一行包含 1,1 和 1,3。我将如何创建一个 postgres 约束来做到这一点?如果我对两行都设置了唯一约束,那么我不能有多个相同的 TableA_id 和多个相同的 TableB_id。

解决办法是什么?

4

2 回答 2

13

您是否尝试将两列都设置为唯一的?

ALTER TABLE LinkTable 
ADD CONSTRAINT LinkTable_Unique UNIQUE (TableA_id, TableB_id);
于 2013-02-06T11:57:09.273 回答
5
create table LinkTable (
    TableA_id integer REFERENCES TableA(id),
    TableB_Id integer REFERENCES TableB(id),
    UNIQUE(tableA_id, tableB_id)
);
于 2013-02-06T11:57:53.397 回答