ITPub博客

首页 > 数据库 > MySQL > 数据库层防止重复提交

数据库层防止重复提交

原创 MySQL 作者:壹頁書 时间:2015-12-18 17:03:29 0 删除 编辑
需求:
    用户反复点击按钮,可能造成重复提交。
    可以限制用户,30s内只能提交1次.
    这种问题还可以衍生为,每个用户每天只能提交三次,等等.

MySQL
create table t (username varchar(10) ,ts timestamp default current_timestamp);

大柴30s内只能提交一次.
  1. insert into  t (username)   
  2. select '大柴' from dual   
  3. where   
  4. (  
  5.     select if(count(*)<=0,1,0) from t   
  6.     where username='大柴'   
  7.     and ts>now()-interval '30' second for update  
  8. )=1;  

或者
  1. insert into  t (username)     
  2. select '大柴' from dual   
  3. where not exists  
  4. (  
  5.     select 1 from t where  
  6.     username='大柴' and   
  7.     ts>now()-interval '30' second for update  
  8. );  


大柴每天只能提交三次
  1. insert into  t (username)   
  2. select '大柴' from dual   
  3. where   
  4. (  
  5.     select if(count(*)<=2,1,0) from t   
  6.     where username='大柴'   
  7.     and ts>date_format(now(),'%Y-%m-%d 00:00:00') for update  
  8. )=1;  


Oracle实现类似需求,还有更多的方式.
比如,小柴每天只能提交三次.但是由于没有使用锁,并发情况下,会产生多插入的情况.
  1. create table t (username varchar2(10),ts date default sysdate);  
  2.  
  3. insert into 
  4. (
  5.     select username from t where username='小柴' and 
  6.     (select count(*) from t where username='小柴')<=2 and 
  7.     ts>trunc(sysdate) 
  8.     with check option
  9. ) values('小柴');  

或者
  1. MERGE INTO t t1  
  2. USING (  
  3.     SELECT COUNT(*) AS c  
  4.     FROM t  
  5.     WHERE username = '小柴'  
  6.         AND ts > trunc(SYSDATE)  
  7. ) t2 ON (t2.c > 2)  
  8. WHEN NOT MATCHED THEN INSERT(USERNAME) VALUES ('小柴');  

Oracle这两种方式,都不能处理并发的问题.大并发情况下,可能会多Insert记录.

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1874705/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339966