INSERT INTO或UPDATE有两个条件

era*_*rtg 0 mysql sql

这个问题乍一看似乎很容易,但我根本没有找到合理时间的解决方案.

考虑一个具有以下特征的表:

ID INTEGER PRIMARY KEY AUTOINCREMENT
name INTEGER
values1 INTEGER
values2 INTEGER
dates DATE
Run Code Online (Sandbox Code Playgroud)

每天生成N个新行,用于将来的日期,以及来自有限列表的"名称".我想在有新数据时插入一个新行,但如果已经有一行包含'name'和'dates',只需更新它.

请注意,当前提出的检查条件的SPROC解决方案是不可行的,因为这是从另一种语言推送的数据.

Dre*_*rew 7

insert on duplicate key update就是为了什么.

它的手册页面就在这里.

诀窍在于表需要具有唯一键(可以是复合键),以便clash可以检测到插入操作.因此,更新将在该行上发生,否则为插入.当然,它可以是主键.

在你的情况下,你可以有一个复合键,如

unique key(theName,theDate)
Run Code Online (Sandbox Code Playgroud)

如果该行已存在,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;
Run Code Online (Sandbox Code Playgroud)

显示结果

select * from myThing;
+----+------+---------+---------+------------+
| id | name | values1 | values2 | dates      |
+----+------+---------+---------+------------+
|  1 |  777 |       1 |       4 | 2015-07-11 |
|  2 |  778 |       1 |       1 | 2015-07-11 |
+----+------+---------+---------+------------+
Run Code Online (Sandbox Code Playgroud)

正如所料,插入重复键更新工作,只有2行.