0

This problem seems easy at first sight, but I simply have not found a solution that is reasonable time wise.

Consider a table with the following characteristics:

ID INTEGER PRIMARY KEY AUTOINCREMENT
name INTEGER
values1 INTEGER
values2 INTEGER
dates DATE

Every day, N amount of new rows are generated, for dates into the future, and with the 'name' coming from a finite list. I would like to insert a new row when there is new data, but if there is already a row with 'name' and 'dates', simply update it.

Please note that a current proposed solution of an SPROC that checks the conditional is not feasible, as this is data being pushed from another language.

erasmortg
  • 3,246
  • 1
  • 17
  • 34
  • 2
    possible duplicate of [Insert into a MySQL table or update if exists](http://stackoverflow.com/questions/4205181/insert-into-a-mysql-table-or-update-if-exists) – John Bupit Sep 08 '15 at 22:57

2 Answers2

7

that is what insert on duplicate key update is for.

The Manual page for it is here.

The trick is that the table needs to have a unique key (can be a composite) so that the clash of doing an insert can be detected. As such, the update to occur on that row, otherwise an insert. It can be a primary key, of course.

In your case, you could have a composite key such as

unique key(theName,theDate)

If the row is already there, the clash is detected, and the update happens.

Here is a complete example

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;

show results

select * from myThing;
+----+------+---------+---------+------------+
| id | name | values1 | values2 | dates      |
+----+------+---------+---------+------------+
|  1 |  777 |       1 |       4 | 2015-07-11 |
|  2 |  778 |       1 |       1 | 2015-07-11 |
+----+------+---------+---------+------------+

As expected, insert on duplicate key update works, just 2 rows.

Drew
  • 24,851
  • 10
  • 43
  • 78
2

This is easy:

  • Create a unique key on the columns to check
  • Use the INSERT .. ON DUPLICATE KEY UPDATE construct
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92