Been looking around the web for a while now and don\'t seem to be able to come across anything similar to what I want. I know it\'s something to do with the way I\'m writing
First, add a UNIQUE
constraint on name, barcode, item, location and price.
ALTER TABLE tableX
ADD CONSTRAINT tableX_UQ
UNIQUE (name, barcode, item, location, price) ;
Then you can use 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
could also be used but there are differences in the behaviour (which especially matter if you have foreign keys). For details, see this question “INSERT IGNORE” vs “INSERT … ON DUPLICATE KEY UPDATE” and the answer by @Bill Kawin which discusses the differences between INSERT IGNORE
, INSERT ... ON DUPLICATE KEY
and REPLACE
.