当前位置:网站首页>唯一性索引与逻辑删除冲突问题解决思路
唯一性索引与逻辑删除冲突问题解决思路
2022-06-30 22:30:00 【YXXYX】
引言
今天做项目中遇到了一个问题:逻辑删除和唯一性索引同时存在的情况下,已经逻辑删除的数据由于唯一性索引的约束无法再次添加,该怎么办?
这个问题在之前做其他项目中也遇到过,当时并没有想到什么好的解决方法,也没有查资料,自己想了一个暴力方法:
我直接把唯一性索引去掉了,然后在代码逻辑实现部分用代码对唯一性索引字段进行了唯一性约束;
这当然也解决了问题,但是这样做本来就是不对的,设计好的数据库怎么能随意修改;
这次又遇到了一样的问题,想到上次的那种方法不仅不合规,而且非常麻烦(为了一个唯一性逻辑判断再调用数据库查询然后再写逻辑判断),这次就找了一下解决方法,下面简单介绍一下;
解决思路
所有解决方法就一个思路:通过逻辑删除字段和约束字段组合为一个索引;
比如有一张teacher表,唯一性索引为name,逻辑删除字段为is_delete:

唯一性索引:

为了解决冲突问题,首先需要修改一下索引,让逻辑删除字段和唯一字段一起作为索引:

但是还需要注意一点:一般我们习惯把逻辑删除字段is_delete设为0存在1删除;但是这里就不能这样了;
比如删除上表中test字段,索引可以看为test和1的组合;再次创建test并不会出现问题,因为新创建的索引为test和0的组合,但是如果再次删除test那么就又出现test和1的组合,索引冲突;
所以我们唯一要做的就是想办法让逻辑删除字段的删除标识唯一,未删除字段不需要改变;
下面有三种方法:
删除标识设置为主键id
因为主键id是唯一的,所以只需要将逻辑删除字段的删除标识设置为主键即可:

但是这种方法我认为如果id过长,会不会占用更多的空间?(个人想法)
就比如这个teacher表中我只把is_delete字段设置为tinyint长度为3,如果主键过长肯定需要修改为bigint,麻烦不说,是不是还占用了更多的空间;

删除标识设置为当前时间
这个方法就类似与将删除标识设置为一个时间戳,因为每一段时间都是不一样的,所以自然也不会有重复一说:
那么获取时间可以使用mysql的Now()函数:

但是这样同样也占用空间,并且该字段调用函数可能会影响sql效率;并不是特别推荐;
删除标识设置为NULL
这个方法就是把删除标识设置为NULL,可以完美解决该问题:

我认为这个方法是最好的,我也是使用的这个方法;

可以看到并不会产生冲突;
注意:逻辑删除字段is_delete要设置允许为null;
总结
我也见了其他方法:比如创建历史表、redis判重、新增字段与索引进行唯一约束…
但是这些方法感觉都没有直接修改来的方便,有点多此一举;
当然以上仅是个人观点,如果有问题欢迎交流;
汇总一下:
边栏推荐
- Graduation project
- 软件确认测试的内容和流程有哪些?确认测试报告需要多少钱?
- Ten of the most heart piercing tests / programmer jokes, read the vast crowd, how to find?
- Yolo target detection
- leetcode:104. Maximum depth of binary tree
- What are database OLAP and OLTP? Same and different? Applicable scenarios
- [Android, kotlin, tflite] mobile device integration depth learning light model tflite (image classification)
- Flip the linked list ii[three ways to flip the linked list +dummyhead/ head insertion / tail insertion]
- Based on the open source stream batch integrated data synchronization engine Chunjun data restore DDL parsing module actual combat sharing
- 后疫情时代,云计算如何为在线教育保驾护航
猜你喜欢
随机推荐
Apache服务器OpenSSL升级
Vite2 is compatible with lower versions of chrome (such as Sogou 80). Some grammars requiring higher versions are processed through polyfills
AtCoder Beginner Contest 255
Interesting plug-ins summary
What are database OLAP and OLTP? Same and different? Applicable scenarios
How to ensure the security of our core drawings by drawing encryption
dba
Summary of interesting websites
A new one from Ali 25K came to the Department, which showed me what the ceiling is
分享十万级TPS的IM即时通讯综合消息系统的架构
Turn: win others' follow with practical actions
Ten of the most heart piercing tests / programmer jokes, read the vast crowd, how to find?
Online education program user login and registration
win11更新后任务栏空白怎么办? win11更新后任务栏空白卡死的解决方法
Failed to configure a DataSource: ‘url‘ attribute is not specified and no embedded datasource could
基于kubernetes平台微服务的部署
D compile time count
腾讯3年,功能测试进阶自动化测试,送给在手工测试中迷茫的你
Technical principle of decentralized exchange system development - digital currency decentralized exchange system development (illustrative case)
“飞桨+辨影相机”成为AI界的“预制菜”,工业AI质检落地更简单









