views:

79

answers:

3

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

mysql> 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.

mysql> 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:

mysql> 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  A: 

INSERT ... ON DUPLICATE KEY UPDATE works similarly to REPLACE in that when a row with an existing (duplicate) key is found, it's actually removed (1 row affected) and then a new row created in its place (1 more row affected), giving the illusion of updating/replacing a row.

BoltClock
Gotcha. Just to verify that this was the case and not actually updating 2 rows as @Pekka seemed to suggest, I ran the original query again against known values and found that only one row was truly affected. Thanks for this!
Josh Smith
+1  A: 

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

ontrack
+3  A: 

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.

ChristopheD
Thanks! Glad to see reference to it in the manual.
Josh Smith