mysql - 在其中一列中具有多个空值的复合唯一键约束
问题描述
我在表 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 列中删除外键。或者我们有任何其他解决方案。
解决方案
该索引可以满足您的要求:
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 网站上的类似问题:具有空值的唯一索引。
推荐阅读
- c# - 从当前月份返回月份名称
- android - Android 测试:java.lang.ClassNotFoundException
- javascript - 如何使用 map 函数在 React.js 上的组件键上显示带有空格的 json
- authorization - DHCP 服务器授权失败,错误代码:20079
- python - 使用 webargs 验证 AWS lambda 中的查询字符串参数和请求正文
- python - 返回所有参数总和的函数
- .htaccess - 暂停站点地图文件的尾部斜杠规则
- c# - 通过 C# 从市场映像中提升 Azure VM
- django - Django-tables2 为列标题指定 verbose_name 无效
- java - 使用应用程序属性文件在本机查询中选择表名?