MySQL ON DUPLICATE KEY UPDATE not working as expected

32 Views Asked by At

I have a table looking something like this

id (Primary Key, Auto increment) user_type name some_column
1 Type 1 Name 1 Some value 1
2 Type 2 Name 2 Some value 2

I want to utilise ON DUPLICATE KEY UPDATE by having the user_type and name as a composite index. I have followed these two answers: MySQL: INSERT or UPDATE if exists, but not based on key column MySQL 'UPDATE ON DUPLICATE KEY' without a unique column?

And I have created a composite index

CREATE INDEX test_table_composite ON test_table (user_type, name)

And then I've tried invoking an insert like this

INSERT INTO test_table (user_type, name, some_column)
VALUES ("Type 1", "Name 1", "Some value 1")
ON DUPLICATE KEY UPDATE
some_column = VALUES(some_column);

Followed by another one

INSERT INTO test_table (user_type, name, some_column)
VALUES ("Type 1", "Name 1", "Some other value")
ON DUPLICATE KEY UPDATE
some_column = VALUES(some_column);

However this results in two inserts instead of an insert and an update. I am assuming that it is using the primary key instead of the index to determine whether it's a duplicate or not. What am I doing wrong and how do I go about fixing it?

0

There are 0 best solutions below