可互换的复合主键

时间:2016-11-10 04:28:16

标签: sql composite-primary-key

我的表格foo只有两个字段:fooIdAfooIdB(两者都是相同类型)。那些是复合主键,所以:

primary key (fooIdA, fooIdB)...

考虑到这一点,我怎样才能使键的所有排列相同?
也就是(fooIdA, fooIdB) = (fooIdB, fooIdA)

2 个答案:

答案 0 :(得分:3)

根据您的DBMS,您可以在表达式上创建唯一索引,以防止插入(1,2)(2,1)

在Postgres和Oracle中你可以这样做:

create unique index unique_combinations 
    on the_table (least(fooida, fooidb), greatest(fooida, fooidb));

答案 1 :(得分:1)

您没有指定您的RDBMS。您还可以使用MAX,MIN值添加计算字段,并在这些计算字段上添加UNIQUE约束。这是MSSQL示例:

CREATE TABLE ATest (id1 int, id2 int);

ALTER TABLE ATest ADD idMax AS (CASE WHEN id1>=id2 THEN id1 ELSE id2 END);  
ALTER TABLE ATest ADD idMin AS (CASE WHEN id1>=id2 THEN id2 ELSE id1 END);  
ALTER TABLE ATest ADD CONSTRAINT UniqueConstCalc UNIQUE(idMax,idMin);

insert into ATest values (1,1);
insert into ATest values (1,2);
insert into ATest values (2,1);

(1 row(s) affected)

(1 row(s) affected)

Msg 2627, Level 14, State 1, Line 3
Violation of UNIQUE KEY constraint 'UniqueConstCalc'. 
Cannot insert duplicate key in object 'dbo.ATest'. 
The duplicate key value is (2, 1).
The statement has been terminated.