overview
ON DUPLICATE KEY UPDATE is mainly used for insert and update operations together. When a piece of data is inserted, the insert operation or update operation will be selected according to the primary key constraint and unique constraint. You can also do batch insert or update operations.
- When the primary key is duplicated, perform the Update operation
- When the primary key is not repeated and the unique constraint field is repeated, perform the Update operation
- When the primary key is not repeated and the unique constraint field is not repeated, perform the Insert operation
grammar
Can also do batch processing
INSERT INTO table(colum1,colum2,colum3...) VALUES (value1,value2,value3...)
ON DUPLICATE KEY UPDATE
colum1 = value1, colum2 = value2, colum3 = value3 ...
example
user table
id is the primary key, code has a unique constraint
insert three records
insert into
`user` (id,code,age,username,password)
values (11,'aa',18,'zhangsan','123'),
(12,'bb',18,'lisi','123'),
(13,'cc',18,'wangwu','123');
Execute the operation
ps: the update operation did not modify the id
insert into
`user` (id,code,age,username,password)
values (11,'aa',18,'zhangsan','123'),
(120,'bb',18,'lisi','123456'),
(13,'cc',18,'wangwu','123456'),
(14,'dd',18,'laoliu','123')
as temp
on duplicate key update
code = temp.code,age = temp.age,username = temp.username,password = temp.password;
Note: here the user zhangsan has not changed, lisi has changed the id and password, wangwu has changed the password, and added a new user record laoliu
Result
zhangsan did not change
lisi password change
wangwu password change
lailiu added successfully