如何在 Oracle 中为 1 列创建具有特定值的约束唯一多列?
How to create constraint unique multiple columns with specific value for 1 colums in Oracle?
我已经创建了具有 5 列的唯一约束,如下所示:
ALTER TABLE CAMPAIGN_MSISDN add CONSTRAINT ADWISER_UNIQUE UNIQUE (campaign_id,
msisdn, running_date, time_frame, status);
此状态有 5 个枚举形式的值。
但我希望 ADWISER_UNIQUE 只检查 2/5 状态中的约束而不是所有状态。我该怎么做。
谢谢大家!
您可以在条件中使用 unique index
。请参阅以下示例:
SQL> create table test123 (col1 number, col2 number, col3 number);
Table created.
SQL> -- You need something like this (solution)
SQL> create unique index test123_ix01 on test123(case when col3 in (1,2) then col1 end,
2 case when col3 in (1,2) then col2 end,
3 case when col3 in (1,2) then col3 end);
Index created.
SQL>
现在,让我们检查它是否有效:
SQL> insert into test123 values (1,2,3);
1 row created.
SQL> insert into test123 values (1,2,3);
1 row created.
SQL> insert into test123 values (1,2,1);
1 row created.
SQL> insert into test123 values (1,2,2); -- this is of your interest -- see col3 value
1 row created.
SQL> insert into test123 values (1,2,2); -- this is of your interest -- see col3 value
insert into test123 values (1,2,2)
*
ERROR at line 1:
ORA-00001: unique constraint (TEJASH.TEST123_IX01) violated
SQL>
SQL> select * from test123;
COL1 COL2 COL3
---------- ---------- ----------
1 2 3
1 2 3
1 2 1
1 2 2
SQL>
哇哦!!!当col3
为2时,它限制了col3
的多个值,并且在col3
为1的情况下表现相同。所有其他状态都允许多次插入。
干杯!!
我已经创建了具有 5 列的唯一约束,如下所示:
ALTER TABLE CAMPAIGN_MSISDN add CONSTRAINT ADWISER_UNIQUE UNIQUE (campaign_id,
msisdn, running_date, time_frame, status);
此状态有 5 个枚举形式的值。 但我希望 ADWISER_UNIQUE 只检查 2/5 状态中的约束而不是所有状态。我该怎么做。 谢谢大家!
您可以在条件中使用 unique index
。请参阅以下示例:
SQL> create table test123 (col1 number, col2 number, col3 number);
Table created.
SQL> -- You need something like this (solution)
SQL> create unique index test123_ix01 on test123(case when col3 in (1,2) then col1 end,
2 case when col3 in (1,2) then col2 end,
3 case when col3 in (1,2) then col3 end);
Index created.
SQL>
现在,让我们检查它是否有效:
SQL> insert into test123 values (1,2,3);
1 row created.
SQL> insert into test123 values (1,2,3);
1 row created.
SQL> insert into test123 values (1,2,1);
1 row created.
SQL> insert into test123 values (1,2,2); -- this is of your interest -- see col3 value
1 row created.
SQL> insert into test123 values (1,2,2); -- this is of your interest -- see col3 value
insert into test123 values (1,2,2)
*
ERROR at line 1:
ORA-00001: unique constraint (TEJASH.TEST123_IX01) violated
SQL>
SQL> select * from test123;
COL1 COL2 COL3
---------- ---------- ----------
1 2 3
1 2 3
1 2 1
1 2 2
SQL>
哇哦!!!当col3
为2时,它限制了col3
的多个值,并且在col3
为1的情况下表现相同。所有其他状态都允许多次插入。
干杯!!