To use INSERT/UPDATE (upsert) method with "ON DUPLICATE KEY" you should have primary key or other UNIQUE constraint.
In example, you do not use primary key column in insert statement - your unique constraint is on column "manufacturers_name", and conflict occurs on this column.
RETURNING caluse is used to return updated/inserted row id (manufacturers_id).
CREATE TABLE manufacturers (
manufacturers_id int(11) NOT NULL AUTO_INCREMENT key,
manufacturers_name varchar(32) unique NOT NULL, -- table manufactures UNIQUE constraint
manufacturers_image varchar(64) DEFAULT NULL
);
INSERT INTO manufacturers (manufacturers_id, manufacturers_name, manufacturers_image)
VALUES (1, 'Name1', NULL);
| manufacturers_id |
manufacturers_name |
manufacturers_image |
| 1 |
Name1 |
null |
New row insert. Returned new row id
INSERT INTO manufacturers (manufacturers_name,manufacturers_image)
values ('Name2', NULL )
ON DUPLICATE KEY
UPDATE manufacturers_name='Name2'
, manufacturers_image = 'MyImage2.jpg'
RETURNING manufacturers_id
;
Query output is
Table after update
| manufacturers_id |
manufacturers_name |
manufacturers_image |
| 1 |
Name1 |
null |
| 2 |
Name2 |
null |
Update existing row. Updated row id returned
INSERT INTO manufacturers (manufacturers_name,manufacturers_image)
values ('Name1', NULL )
ON DUPLICATE KEY
UPDATE manufacturers_name='Name1-n'
, manufacturers_image = 'MyImage1.jpg'
RETURNING manufacturers_id
;
Query output is
Table after update
| manufacturers_id |
manufacturers_name |
manufacturers_image |
| 1 |
Name1-n |
MyImage1.jpg |
| 2 |
Name2 |
null |
fiddle
Pay attention: The row/s affected value is reported as 1 if a row is inserted, and 2 if a row is updated
Link
... returning ...: mariadb.com/docs/server/reference/sql-statements/…