在 MySQL 中实现 INSERT ... ON DUPLICATE KEY UPDATE

mysqlmysqli database

INSERT ... ON DUPLICATE KEY UPDATE 的工作方式是,如果发现重复的唯一键或主键,它将执行 UPDATE。仅当出现重复值时才执行 UPDATE。

首先我们创建一个表 −

mysql> create table DemoTable733 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(100),
   StudentMarks int,
   UNIQUE KEY Un_Name (StudentName)
);
Query OK, 0 rows affected (0.60 sec)

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

mysql> insert into DemoTable733(StudentName,StudentMarks) values('John',45) 
ON DUPLICATE KEY UPDATE StudentMarks=86;
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable733(StudentName,StudentMarks) values('Adam',65) 
ON DUPLICATE KEY UPDATE StudentMarks=86;
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable733(StudentName,StudentMarks) values('Carol',75) 
ON DUPLICATE KEY UPDATE StudentMarks=86;
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable733(StudentName,StudentMarks) values('John',45) 
ON DUPLICATE KEY UPDATE StudentMarks=86;
Query OK, 2 rows affected (0.12 sec)

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

mysql> select *from DemoTable733;

这将产生以下输出 -

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
| 1         | John        | 86           |
| 2         | Adam        | 65           |
| 3         | Carol       | 75           |
+-----------+-------------+--------------+
3 rows in set (0.00 sec)

相关文章