在 MySQL 中实现 INSERT… ON DUPLICATE KEY UPDATE

mysqlmysqli database

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

首先我们创建一个表 −

mysql> create table DemoTable
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.61 sec)

这是创建索引的查询 −

mysql> create unique index value_index on DemoTable(Value);
Query OK, 0 rows affected (0.77 sec)
Records: 0 Duplicates: 0 Warnings: 0

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

mysql> insert into DemoTable values(40) on duplicate key update Value=Value+1000;
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(50) on duplicate key update Value=Value+1000;
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(40) on duplicate key update Value=Value+1000;
Query OK, 2 rows affected (0.15 sec)

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

mysql> select *from DemoTable;

这将产生以下输出 −

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

相关文章