MySQL对主键重复的处理

在向一个表中插入数据的时候,有一种常见的需求:判断插入的值是否在表中已经存在,如果是则执行update操作,否则执行insert。在Oracle里可以使用merge into来实现,MySQL也对标准SQL进行了扩展来实现此功能。

1. replace into
replace类似于insert,区别在于如果新插入的行的主键或唯一索引值已存在,则先删除相应的行在插入新行。除非表有主键或唯一索引,否则replace不会执行判重,从而等同于insert。如果表中有多个唯一索引,则replace into一行前可能会先删除多行。例子:

  1. create table t1 ( a int not null primary key);  
  2. replace into t1 values (1);  
  3. select row_count();  
  4. replace into t1 values (1);  
  5. select row_count();  
  6. replace into t1 values (1);  
  7. select row_count();  
  8. select * from t1;  
  9.   
  10. drop table t1;  
  11.   
  12. create table t1 ( a int not null unique key, b int not null unique key);  
  13. insert into t1 values (1,2);  
  14. insert into t1 values (2,3);  
  15. select * from t1;  
  16. replace into t1 values (1,3);  
  17. select row_count();  
  18. select * from t1;  


2. insert...on duplicate key update
与replace into类似,也是在insert时执行主键或唯一索引判重,如果重复则执行相应的update操作。如果存在多个唯一索引且重复的行多于一行,则只修改一行。例子:

  1. create table t1 ( a int not null unique key, b int not null unique key, c int not null);  
  2. insert into t1 values (1,1,1);  
  3. insert into t1 values (2,2,1);  
  4. select * from t1;  
  5. insert into t1 values (1,2,3) on duplicate key update c=c+1;  
  6. select row_count();  
  7. select * from t1;  
  8. insert into t1 values (1,2,3) on duplicate key update c=c+1;  
  9. insert into t1 values (1,2,3) on duplicate key update c=c+1;  
  10. select * from t1;  


可以使用values函数在update子句里引用新插入的值,这在同时插入多个值时很有用:

  1. create table t1 ( a int not null unique key, b int not null unique key, c int not null);  
  2. insert into t1 values (1,2,3),(4,5,6) on duplicate key update c=values(a)+values(b);  
  3. select * from t1;  
  4. insert into t1 values (1,2,3),(4,5,6) on duplicate key update c=values(a)+values(b);  
  5. select * from t1; 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值