Mysql:INSERT ON DUPLICATE KEY UPDATE

1,212 阅读1分钟

INSERT ON DUPLICATE KEY UPDATE是mysql对标准sql的扩展,用于新增或更新一行记录。 它的基本语法:

INSERT INTO table (column_a,column_b,...)
VALUES (va,vb,...)
ON DUPLICATE KEY UPDATE
   c1 = v1, 
   c2 = v2,
   ...;

当该行存在时,会更新列值,不存在时,会插入新行。

关键在于insert字句的字段中,它们必须有是属于唯一索引或是主键的,这样才会起到【新增或更新】的作用。在上述的语法例子中,column_a,column_b,... 至少有一个字段是主键或唯一索引。



MySQL returns the number of affected rows based on the action it performs:

  • If the new row is inserted, the number of affected rows is 1.

  • If the existing row is updated, the number of affected rows is 2.

  • If the existing row is updated using its current values, the number of affected rows is 0.

  • 如果新增一行,影响行数为1。

  • 如果更新已存在行,影响行数为2。

  • 如果更新的值跟改行记录原本的值一样,那么影响的行数为0。



利用insert字句的值去应用于on duplicate key update字句是一个很常见的需求,我们可以用values()函数去做到这一点。如:

INSERT INTO `user` (id,name,age) values(2,'sss',99) ON DUPLICATE KEY UPDATE `id` = VALUES(id) ,`name`=VALUES(name),`age`=VALUES(age);

上面这条sql的作用就是新增一条id为2的记录(假设id这个字段为主键)。

如果id为2的记录已存在,那么就更新id,name,age这3个字段的值,更新的值采用insert字句的值,即更新为:id = 2,name = 'sss',age = 99