【问题标题】:How to create constraint unique multiple columns with specific value for 1 colums in Oracle?如何在 Oracle 中为 1 列创建具有特定值的约束唯一多列?
【发布时间】:2019-11-11 04:24:06
【问题描述】:

我已经创建了具有 5 列的唯一约束,如下所示:

 ALTER TABLE CAMPAIGN_MSISDN add CONSTRAINT ADWISER_UNIQUE UNIQUE (campaign_id, 
 msisdn, running_date, time_frame, status);

此状态有 5 个枚举形式的值。 但我希望 ADWISER_UNIQUE 只检查 2/5 状态中的约束而不是所有状态。我该怎么做。 谢谢大家!

【问题讨论】:

  • 我的“只检查 2/5 状态而不是所有状态的约束”是什么意思?

标签: oracle unique-constraint


【解决方案1】:

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

干杯!!

【讨论】:

  • 如果这个答案解决了你的问题,那么请accept它,这样你的问题就会被标记为已解决。
猜你喜欢
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多