这个问题乍一看似乎很简单,但我只是没有找到合理的时间明智的解决方案。
考虑一个具有以下特征的表:
ID INTEGER PRIMARY KEY AUTOINCREMENT
name INTEGER
values1 INTEGER
values2 INTEGER
dates DATE
每天都会生成 N 个新行,用于将来的日期,并且“名称”来自有限列表。我想在有新数据时插入新行,但如果已经有包含“名称”和“日期”的行,只需更新它即可。
请注意,当前提出的用于检查条件的 SPROC 解决方案是不可行的,因为这是从另一种语言推送的数据。
最佳答案
这就是插入重复 key 更新
的用途。
它的手册页是 here .
诀窍是表需要有一个唯一的键(可以是复合键),以便可以检测到执行插入时的冲突
。因此,更新发生在该行上,否则发生插入。当然,它可以是主键。
就您而言,您可以有一个复合键,例如
unique key(theName,theDate)
如果该行已经存在,则会检测到冲突
,并进行更新。
这是一个完整的示例
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 行。
关于mysql - INSERT INTO 或 UPDATE 有两个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39926125/