Primero, agrega un UNIQUE
restricción de nombre, código de barras, artículo, ubicación y precio.
ALTER TABLE tableX
ADD CONSTRAINT tableX_UQ
UNIQUE (name, barcode, item, location, price) ;
Luego puede usar INSERT INTO ... ON DUPLICATE KEY UPDATE
:
INSERT INTO tableX
(name, barcode, item, location, price, quantity, date)
VALUES
(?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
quantity = CASE WHEN VALUES(date) > date
THEN quantity + VALUES(quantity) -- add quantity
ELSE quantity -- or leave as it is
END
, date = CASE WHEN VALUES(date) > date
THEN VALUES(date) ; -- set date to new date
ELSE date -- or leave as it is
END
REPLACE
también podría usarse, pero hay diferencias en el comportamiento (que son especialmente importantes si tiene claves externas). Para obtener más información, consulte esta pregunta “INSERT IGNORE ” frente a “INSERTAR… EN ACTUALIZACIÓN DE CLAVE DUPLICADA”
y la respuesta de @Bill Kawin que analiza las diferencias entre INSERT IGNORE
, INSERT ... ON DUPLICATE KEY
y REPLACE
.