简体   繁体   English

SQL唯一键iff未删除

[英]SQL Unique Key iff not Deleted

I have table as below: 我有如下表:

+----------+---------+
| ParentId | ChildId |
+----------+---------+

It is a one-to-many relationship (one parent, multiple children) at the moment the primary key is the child id because a child can only map to one parent (all pretty straight forward so far). 目前,这是一对多的关系(一个父母,多个孩子),因为孩子的身份只能映射到一个父母(到目前为止都很简单),所以主键是孩子的ID。
My question comes in now tho I want to add a secondary column as below: 我的问题现在出现了,我想添加第二列,如下所示:

+----------+---------+---------+
| ParentId | ChildId | Deleted |
+----------+---------+---------+

So the situation is I need to keep track, for audit reasons, mappings of deleted parents, my thought was to make Child Id unique iff Deleted is well false. 因此,由于审计原因,我需要保持跟踪,删除父母的映射,我的想法是使Child Id唯一(如果Deleted是错误的)。 Question is how do I achieve this? 问题是我该如何实现? Is it possible or should a create a secondary table that I used to archive the deleted entries, any other suggest how I can either achieve this or another approach I can take? 是否可以或者应该创建一个用于存储已删除条目的辅助表,是否还有其他建议建议我如何实现此目的或可以采用的另一种方法?

I think this is your question: 我认为这是您的问题:

my thought was to make Child Id unique iff Deleted is well false. 我的想法是使Child Id唯一,如果Deleted是错误的。 Question is how do I achieve this? 问题是我该如何实现?

If so, you can use a filtered unique index: 如果是这样,则可以使用过滤后的唯一索引:

create unique index unq_t_parent_child on t(parent, child)
    where isdeleted = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM