MySQL 为什么我的“INSERT ... ON DUPLICATE KEY UPDATE”中有两行受到影响?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3747314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:11:48  来源:igfitidea点击:

Why are 2 rows affected in my `INSERT ... ON DUPLICATE KEY UPDATE`?

mysqlinsertinsert-update

提问by Josh Smith

I'm doing an INSERT ... ON DUPLICATE KEY UPDATEfor a PRIMARY KEYin the following table:

我正在INSERT ... ON DUPLICATE KEY UPDATEPRIMARY KEY下表中的a做一个:

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.

但是,即使这些值应该是唯一的,我也看到有 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)

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

回答by ChristopheD

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.

使用 ON DUPLICATE KEY UPDATE,如果将行作为新行插入,则每行的受影响行值为 1,如果更新现有行,则为 2。

回答by ontrack

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

所以你知道你是更新了一行(重复键)还是只是插入了一个:http: //dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html