First I must say you keep saying database
. You mean table
.
Schema
CREATE TABLE distribuzioni
( id int primary key auto_increment,
nazione varchar(100) NOT NULL,
categoria varchar(100) NOT NULL,
risultato varchar(100) NOT NULL,
densita FLOAT(3,2),
unique key(nazione,categoria,risultato) -- this is important
);
Let's start with some data in our table.
insert distribuzioni(nazione,categoria,risultato,densita)
values ('Italy','fish','thing1',1.23);
select * from distribuzioni;
+----+---------+-----------+-----------+---------+
| id | nazione | categoria | risultato | densita |
+----+---------+-----------+-----------+---------+
| 1 | Italy | fish | thing1 | 1.23 |
+----+---------+-----------+-----------+---------+
That was previous data above. A starting point.
Below is how new data goes in as you want:
insert distribuzioni(nazione,categoria,risultato,densita)
values ('France','cars','thing8',1.11)
on duplicate key update densita=1.11;
insert distribuzioni(nazione,categoria,risultato,densita)
values ('Italy','fish','thi1ng1',5.11)
on duplicate key update densita=5.55;
.
select * from distribuzioni;
+----+---------+-----------+-----------+---------+
| id | nazione | categoria | risultato | densita |
+----+---------+-----------+-----------+---------+
| 1 | Italy | fish | thing1 | 5.55 |
| 2 | France | cars | thing8 | 1.11 |
+----+---------+-----------+-----------+---------+
Important point. If you do not make the unique composite key on those three columns, the update will not fire off and you will get another row that you do not want.
Also, and I am just saying this to save you the suspense, each time the update triggers, even though you get the update you want, it will increment internally to the table (not in a row) the next available auto inc number. So that is a side-effect
. Try it out, you will see what I mean. Your data will be fine, but you will get gaps.
Here is the manual page on Insert on Duplicate Key Update
Remember, without the unique composite key, this will not work. So do not waste your time on it, without it. What is a unique composite key you ask? It is the line in the Schema shown that says next to it -- this is important
. And it means that there can only be one row in that table with a combination of those three values as a combination. That is the magic that makes it insert or update.