mysql防止重复提交解决方案

论坛 期权论坛 脚本     
匿名技术用户   2020-12-30 07:49   34   0

mysql防止重复提交解决方案

1.案例场景

我们平时在做web项目过程中避免不了需要往数据库表中插入或者批量插入数据,比如现在有一张会员表

t_member(id,configId,memberId,memberName,mobile) id 自增的,现在有一个需求是这样的,我们给某一个门店添加新会员,并给这些新会员发送节日短信,有这样一个场景,我第一次添加了5个会员的信息,分别是会员a,b,c,d,e, 我第二次又添加10个会员 分别是会员a-j,这里面a-e会员已经添加过了,如果不做约束的话会员会被重复提交,也就是在web层我们添加之前需要校验去判断会员信息是否存在,如果不存在就添加,这个过程会员数量量大的情况,逐个比较会增加内存开销,所以我们从数据库层考虑如何避免重复提交的问题

2.解决方案

1.建立联合唯一索引

给表建立联合唯一索引目的是不希望表中有两条重复的记录

alter table t_member add unique index(configId,memberId);

不允许t_member表中configId,memberId有重复的记录

2.另外在sql中使用insert ignore into 忽略重复记录

这样重复的记录将不会被插入到表中

select appId,openId,count(*) as count from `t_table` group by appId,openId having count>1; 
select `toUserPhone`, count(*) as count from `gift_record` group by toUserPhone having count>1; 
select `customerId`,`brandCode`, count(*) as count from `t_data_source` group by brandCode having count>1; 

3.删除数据库中重复的数据,并保留序号最小的一条数据

delete from `school`
where id not in(select * from (select id from school group by `school_name`)as b);

转载于:https://my.oschina.net/chenxiaobian/blog/749064

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP