100
votes

I'm doing an INSERT ... ON DUPLICATE KEY UPDATE for a PRIMARY KEY in the following table:

DESCRIBE users_interests;
+------------+---------------------------------+------+-----+---------+-------+
| Field      | Type                            | Null | Key | Default | Extra |
+------------+---------------------------------+------+-----+---------+-------+
| uid        | int(11)                         | NO   | PRI | NULL    |       |
| iid        | int(11)                         | NO   | PRI | NULL    |       |
| preference | enum('like','dislike','ignore') | YES  |     | NULL    |       |
+------------+---------------------------------+------+-----+---------+-------+

However, even though these values should be unique, I'm seeing 2 rows affected.

INSERT INTO users_interests (uid, iid, preference) VALUES (2, 2, 'like')
ON DUPLICATE KEY UPDATE preference='like';
Query OK, 2 rows affected (0.04 sec)

Why is this happening?

EDIT

For comparison, see this query:

UPDATE users_interests SET preference='like' WHERE uid=2 AND iid=2;
Query OK, 1 row affected (0.44 sec)
Rows matched: 1  Changed: 1  Warnings: 0
2
Why do you have two primary keys in the first place?Pekka
@Pekka, the PRIMARY KEY is a single pk created on (uid, iid) since most queries will be run when both values are known.Josh Smith
@Josh I see. The manual seems to discourage it though: In general, you should try to avoid using an ON DUPLICATE KEY UPDATE clause on tables with multiple unique indexes. Does it need to be a primary key? Why not a normal index?Pekka
@Pekka, honestly not sure. I'm still relatively new to this. Does an index make more sense in this case?Josh Smith
@Josh yup, a normal index spanning both columns should would work fine herePekka

2 Answers

213
votes

From the manual:

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated.

7
votes

So you know whether you updated a row (duplicate key) or just inserted one: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html