I want to INSERT a new record into my database if it is no exists, otherwise it will UPDATE those existing records.
I did search on Stackoverflow, but none of the result can solve my issue.
- "INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
- MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query
SCENARIO
There are a lot of records inside Purchase Details table. So the only Unique ID is only purchase_id.
I want to update the amount which have the same product_id. Refer to the table.
Below is the SQL Query I have tried so far.
INSERT INTO `purchase_details` (`product_id`, `amount`)
VALUES (1583, 0)
ON DUPLICATE KEY UPDATE amount = 0
The query shows 1 row affected.
But total has 146 rows which mean this query is not working.
PROBLEM
- ON DUPLICATE KEY UPDATE only allow to inserted a row that would cause a duplicate value in a UNIQUE index or PRIMARY KEY
amount
column? – Sameer MirjiON DUPLICATE KEY UPDATE
will not help here :( – Jimish Gamit