在向 MySQL 中插入一条记录的时候,如果基于自增主键或唯一索引键来判断该记录存在的话,则更新该记录;如果不存在,则插入该记录。这就是语法 insert into … on duplicate key update 的功能。其中,基于主键还是唯一索引键的判断依据是根据表达式中的字段名称来确定的。具体见以下示例:
With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to the mysql_real_connect() C API function when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values.
:
对于每一行记录来说,如果执行结果是新增了,受影响行数为 1;如果对应记录被更新了,受影响行数为 2;如果当前记录和要更新为的记录数据一致,受影响行数为 0 。如果在连接 mysql 服务时 CLIENT_FOUND_ROWS 参数是 mysql_real_connect(),上文最后一种情况的受影响行数为 1 而不是 0 。
本示例所用 MySQL 版本为 5.5.53,存储引擎为 Innodb
参考 MySQL 官网资料地址:https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
表结构
create table t (
id int unsigned not null auto_increment,
a_id int unsigned not null,
b_id int unsigned not null,
v int unsigned not null,
primary key (id),
unique index `uk_a_b` (a_id, b_id)
) engine = innodb default charset = utf8;
第一次插入数据(插入了一条新记录)
基于唯一索引插入同样的数据(更新了数据且自增值 +1)