数据表开始时未建唯一索引的补救办法
业务场景
在开始设计表时未添加唯一索引,在需求迭代过程中需要保证某些字段的唯一性,如果直接建立唯一索引,会报错。
如果又想保留历史数据,又想在以后的数据插入时保证某些字段的唯一性,该怎么办呢?
解决方案
假设需要bc需要保证唯一性
<insert id="batchInsert">
insert into 表
(a, b, c ,d, e)
values
<foreach collection="insurancePerformanceDetailDOS" item="item" index="index" open="" close="" separator=",">
select
(
#{a}, #{b}, #{c}, #{d} # 全量的数据
)
where not exists (
select 1 from
表 where
b = #{b} and c = #{c}
)
</foreach>
</insert>
解释: 首先从表中查找 b = #{b} 、c = #{c}的数据,
① 若存在,则 not exist() 返回fasle ,那么以下的整个sql会返回null,则该条数据不会被插入。
② 若不存在,则#{a}、#{b}、#{c}、#{d} (要插入的全量数据 )会返回,此时就会被插入到表中。
select
(
#{a}, #{b}, #{c}, #{d}
)
where not exists (
select 1 from
表 where
b = #{b} and c = #{c}
)