We have a dynamic query that inserts data from a CSV file, what we want is to update all the rows even if there are duplicates.
We know that this works:
INSERT INTO TABLE (ID1,ID2,ID3,PAYDATE,PRICE,CURRENCY)
VALUES ('75','2','16','2018-11-5','300','CAD'),
('75','2','17','2018-11-10','400','USD')
ON DUPLICATE KEY UPDATE
ID1=VALUES(ID1),
ID2=VALUES(ID2),
ID3=VALUES(ID3),
PAYDATE=VALUES(PAYDATE),
PRICE=VALUES(PRICE),
CURRENCY=VALUES(CURRENCY)
But this can become complicated when creating a dynamic query, where we don't know the table structure before hand. So we are looking for a query similar to this:
INSERT INTO TABLE (ID1,ID2,ID3,PAYDATE,PRICE,CURRENCY)
VALUES ('75','2','16','2018-11-5','300','CAD'),
('75','2','17','2018-11-10','400','USD')
ON DUPLICATE KEY UPDATE
(ID1,ID2,ID3,PAYDATE,PRICE,CURRENCY)
VALUES(ID1,ID2,ID3,PAYDATE,PRICE,CURRENCY)
This last one obviously doesn't work but it is easier for us to work with it because we already have the columns in a single string and the first query requires exploding the string into an array and execute a few nested loops.
//PHP
$cols = "ID1,ID2,ID3,PAYDATE,PRICE,CURRENCY";
$vals = "('75','2','16','2018-11-5','300','CAD'),
('75','2','17','2018-11-10','400','USD')";
$query = "INSERT INTO TABLE ($cols)
VALUES $vals
ON DUPLICATE KEY UPDATE
($cols) VALUES($cols)";
Is there a similar way?
INSERT INTO- wheres the problem, repeating them in theON DUPLICATE KEYStatement?REPLACEquery instead ofINSERT, it allows that kind of syntax. However, it has the misfeature that instead of updating rows, it deletes them and recreates them.