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

时间:2019-01-21 09:50:34

标签: mysql sql sql-server oracle

我在表x上有一个唯一的键,该键具有3列(a,b,c),其中a,b,c是外键,而在x表中c可以为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列中删除外键。或者我们有其他解决方案。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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为空时,这将允许多个值。