那
insert on duplicate key update是为了什么
手册页面在这里。
诀窍是表需要具有唯一键(可以是复合键),以便
clash可以检测到插入操作。这样,将在该行上进行更新,否则将进行插入。当然,它可以是主键。
就您而言,您可以使用一个组合键,例如
unique key(theName,theDate)
如果该行已经存在,则将
clash检测到该行,然后进行更新。
这是一个完整的例子
create table myThing( id int auto_increment primary key, name int not null, values1 int not null, values2 int not null, dates date not null, unique key(name,dates) -- <---- this line here is darn important);insert myThing(name,values1,values2,dates) values (777,1,1,'2015-07-11') on duplicate key update values2=values2+1;insert myThing(name,values1,values2,dates) values (778,1,1,'2015-07-11') on duplicate key update values2=values2+1;-- do the 1st one a few more times:insert myThing(name,values1,values2,dates) values (777,1,1,'2015-07-11') on duplicate key update values2=values2+1;insert myThing(name,values1,values2,dates) values (777,1,1,'2015-07-11') on duplicate key update values2=values2+1;insert myThing(name,values1,values2,dates) values (777,1,1,'2015-07-11') on duplicate key update values2=values2+1;
显示结果
select * from myThing;+----+------+---------+---------+------------+| id | name | values1 | values2 | dates |+----+------+---------+---------+------------+| 1 | 777 | 1 | 4 | 2015-07-11 || 2 | 778 | 1 | 1 | 2015-07-11 |+----+------+---------+---------+------------+
如预期的那样,在重复的密钥更新上插入仅2行。



