如何在Oracle中为1个列创建具有特定值的约束唯一多列?

问题描述 投票:0回答:1

我已经创建了具有5列的唯一约束,如下所示:ALTER TABLE CAMPAIGN_MSISDN添加CONSTRAINT ADWISER_UNIQUE UNIQUE(campaign_id,msisdn,running_date,time_frame,status);status具有5枚举形式的值。但是我希望ADWISER_UNIQUE仅检查2/5状态下的约束,而不是所有状态。我该怎么做。谢谢大家!

oracle unique-constraint
1个回答
0
投票

您可以在条件下使用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的情况下,其行为相同。允许所有其他状态多次插入。

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.