INSERT INTO contactos
(iduser, tipo, codigo, nombre, dni_nif )
VALUES
('1','cliente','1','Juan','500000'),
('1','cliente','2','Maria','500001'),
('2','cliente','1','Sara','500002')
ON DUPLICATE KEY UPDATE
codigo = codigo,
iduser = iduser;
In MySQL : iduser+codigo
(unique key)
iduser = code assigned to the client
code = key of the contact of each client
I have the previous query, the first time it is executed it works fine, but if the client decides to re-upload the data ( excel ) to update the existing ones and/or add new clients, I can't get it to update the existing ones.
Where is the problem?
Mario.
From what I see in the query you make, you are trying to modify the code and id_user fields in the update. Which doesn't make sense, since it would assign them the same, values. There, what you have to use are the rest of the fields: type, name and dni_nif, which are the ones you have to update.
Suppose we have this table:
And we want to insert or update (like what you're doing), we have two options:
1 - REPLACE
What the replace command does is execute an insert, but if it finds that the record to be inserted has an index that already exists (primary or unique), it deletes it first and inserts the new one. For example:
And the result will be:
2 - INSERT ... ON DUPLICATE KEY UPDATE
For our case it would be:
And the result it gives us:
The problem is that you are using a query
INSERT
to modify the existing data, and you should use a queryUPDATE
, since itINSERT
will always try to insert the data into the table, and if there are duplicate keys you get the error you mentioned (ON DUPLICATE KEY
).You should run a query similar to the following when trying to modify existing data in a table: