MarmiteBomber 的方法略有不同,以避免连接值(这可能导致与非整数值发生意外冲突):
create table t (a number, b number, c varchar2(5),
constraint t_chk check (c in ('true', 'false'))
);
create unique index t_unq
on t (case when c = 'true' then a end, case when c = 'true' then b end);
insert into t(a,b,c) values (1,2,'true');
1 row inserted.
insert into t(a,b,c) values (1,2,'false');
1 row inserted.
insert into t(a,b,c) values (1,2,'false');
1 row inserted.
insert into t(a,b,c) values (1,2,'true');
ORA-00001: unique constraint (MY_SCHEMA.T_UNQ) violated
select * from t;
A B C
---------- ---------- -----
1 2 true
1 2 false
1 2 false
为什么非整数(如果它们可以存在)可能是一个问题的快速示例:
create unique index uq_true on test(case when c = 'true' then a||'.'||b end);
insert into test(a,b,c) values (1.1, 2,'true');
1 row inserted.
insert into test(a,b,c) values (1, 1.2,'true');
ORA-00001: unique constraint (MY_SCHEMA.UQ_TRUE) violated
select * from test;
A B C
---------- ---------- -----
1.1 2 true
...因为'1.1' ||'.'|| '2' 和'1' ||'.'|| '1.2' 都解析为相同的字符串'1.1.2'。
在组合字符串值而不是数字时,这也可能是一个问题。在任何一种情况下,您都可以通过使用任何一个值中都不存在的分隔符来避免它;字符串更难处理,但对于数字,除了句号(或逗号以确保安全)之外的任何标点符号都可能会这样做 - 除非有人对 nls_numeric_characters 有奇怪的设置...