首页 > 解决方案 > 在其中一列中具有多个空值的复合唯一键约束

问题描述

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

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 列中删除外键。或者我们有任何其他解决方案。

标签: mysqlsqlsql-serveroracle

解决方案


该索引可以满足您的要求:

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 网站上的类似问题:具有空值的唯一索引


推荐阅读