(转载)INSERT INTO .. ON DUPLICATE KEY 语法与实例教程

(转载)http://www.111cn.net/database/mysql/ON_DUPLICATE_KEY%20.htm

INSERT语句末尾指定了ON DUPLICATE KEY UPDATE,并且插入行后会导致在一个UNIQUE索引或PRIMARY KEY中出现重复值,则执行旧行UPDATE;如果不会导致唯一值列重复的问题,则插入新行。例如,如果列a被定义为UNIQUE,并且包含值1,则以下两个语句具有相同的效果:

insert into table (a,b,c) 
values (1,2,3) on duplicate key update c=c+1;

update table set c=c+1 where a=1;

如果insert多行记录, on duplicate key update后面字段的值怎么指定?要知道一条insert语句中只能有一个on duplicate key update

insert into table (a,b,c) values 
(1,2,3),
(2,5,7),
(3,3,6),
(4,8,2),
on duplicate key update b=values(b);
insert into table (a,b,c) values 
(1,2,3),
(2,5,7),
(3,3,6),
(4,8,2),
on duplicate key update b=values(b);

insert [low_priority | delayed | high_priority] [ignore] [into] tbl_name [(col_name,...)] values ({expr | default},...),(...),... [ on duplicate key update col_name=expr, ... ]或:

insert [low_priority | delayed | high_priority] [ignore] [into] tbl_name set col_name={expr | default}, ... [ on duplicate key update col_name=expr, ... ]或:

insert [low_priority | high_priority] [ignore] [into] tbl_name [(col_name,...)] select ... [ on duplicate key update col_name=expr, ... ]insert用于向一个已有的表中插入新行。insert...values和insert...set形式的语句根据明确指定的值插入行。insert...select形式的语句插入从其它表中选出的行。在13.2.4.1节,“insert ... select语法”中对insert...select进行了进一步的讨论。

行应被插入到tbl_name表中。可以按以下方法指定列。本语句向这些列提供值。

· 列名称清单或set子句明确的指示了列。

· 如果您不为insert...values或insert...select指定列的清单,则表中每列的值必须在values清单中提供,或由select提供。如果您不知道表中各列的顺序,则使用describe tbl_name查询。

例子:

mysql> select * from student;
+-----+--------+
| age | energy |
+-----+--------+
|   1 |      0 |
|   2 |      0 |
|   3 |      0 |
|   7 |      0 |
|   8 |      0 |
|   9 |      0 |
+-----+--------+
6 rows in set (0.00 sec)

mysql> insert into student (age, energy) values(1, 1), (2, 2), (3, 3) on duplica
te key update energy=values(energy);
Query OK, 6 rows affected (0.00 sec)
Records: 3  Duplicates: 3  Warnings: 0

mysql> select * from student;
+-----+--------+
| age | energy |
+-----+--------+
|   1 |      1 |
|   2 |      2 |
|   3 |      3 |
|   7 |      0 |
|   8 |      0 |
|   9 |      0 |
+-----+--------+
6 rows in set (0.00 sec)

mysql>
原文地址:https://www.cnblogs.com/Robotke1/p/3192480.html