复合唯一键约束,其中一列中包含多个空值

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

我在表x上有一个唯一的键,有3列(a,b,c),其中a,b,c是外键,c在x表中可以为null。

a b c
- - ----
1 1    1
1 1    2
1 1 NULL
1 1 NUll

上面的行在MySQL上是有效的,并且插入多个null的行不会违反约束。但是,对于Oracle,SQL-Server,情况并非如此。

这种情况下的最佳做法是什么?

每个唯一约束都会创建唯一索引,如果我禁用唯一索引,SQL-Server中也允许多个空值(带过滤索引)

我需要在列c中设置多个值,并将null作为其外键。

如果我从表x中的c列中删除外键,请建议我应该删除唯一键约束。或者我们有任何其他解决方案。

mysql sql sql-server oracle
2个回答
2
投票

这个索引做你想要的:

create unique index idx_t_abc on t(
  case when c is not null then a end,
  case when c is not null then b end, 
  case when c is not null then c end);

仅在Oracle中测试过。在asktom网站上的类似问题:unique index with null values


0
投票

在SQL Server中,您可以使用筛选的索引:

create index unq_t_a_b_c on t(a, b, c)
    where c is not null;

这也适用于Postgres和Postgres派生的数据库。

Oracle不支持筛选索引。您可以使用计算列来实现此目的 - 假设您有一个主键:

create index unq_t_a_b_c on t(a, b, c, (case when c is null then pk end));

c为null时,这将允许多个值。

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