在MySQL中实现INSERT…ON DUPLICATE KEY UPDATE

如果该行在UNIQUE索引或PRIMARY KEY中导致重复,则在向表中插入新行时会出现错误。要解决此问题,请使用ON DUPLICATE KEY UPDATE。在INSERT语句中使用此功能时,现有行将使用新值进行更新。

让我们首先创建一个表-

mysql> create table DemoTable
   -> (
   -> Value int
   -> );

这是创建索引的查询-

mysql> create unique index value_index on DemoTable(Value);
Records: 0 Duplicates: 0 Warnings: 0

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable values(40) on duplicate key update Value=Value+1000;
mysql> insert into DemoTable values(50) on duplicate key update Value=Value+1000;
mysql> insert into DemoTable values(40) on duplicate key update Value=Value+1000;

使用select语句显示表中的所有记录-

mysql> select *from DemoTable;

这将产生以下输出-

+-------+
| Value |
+-------+
|    50 |
|  1040 |
+-------+
2 rows in set (0.00 sec)