我正在INSERT ... ON DUPLICATE KEY UPDATE为PRIMARY KEY下表做一个:
INSERT ... ON DUPLICATE KEY UPDATE
PRIMARY KEY
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 | | +------------+---------------------------------+------+-----+---------+-------+
但是,尽管这些值应该是唯一的,但我发现有2行受到影响。
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)
为什么会这样呢?
编辑
为了进行比较,请参见以下查询:
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
从手册:
使用ON DUPLICATE KEY UPDATE,如果将行作为新行插入,则每行的受影响行值为1;如果更新现有行,则为2。