POSTGRES:
1、创建表
create table tbl_user(
id serial PRIMARY KEY,
name varchar(256),
addr varchar(256),
age int,
score int,
fav varchar(256)
);
2、创建唯一约束
alter table tbl_user add constraint name_add_age_unique unique(name,addr,age);
3、首先插入两条数据
INSERT INTO tbl_user
(name, addr, age, score, fav)
VALUES
('aaa','aaa_addr',10,22,'aaa_fav'),
('bbb','ccc_addr',10,22,'bbb_fav');
4、此时直接INSERT INTO 主键重复的数据,会直接报唯一键冲突,插入失败
INSERT INTO tbl_user
(name, addr, age, score, fav)
VALUES
('aaa','aaa_addr',10, 23,'aaa_fav_new'),
('bbb','ccc_addr',10, 23,'bbb_fav_new'),
('ddd','ddd_addr',10, 22,'ccc_fav'),
('eee','eee_addr',10, 22,'ddd_fav');
5、采用UPDATE_INSERT方式,插入成功,并且对冲突列执行指定更新操作
语法说明:
1、ON conflict(唯一约束键列表) DO,用于指定对于冲突的唯一键,可以是联合唯一键
2、excluded.列名 用于获取插入的时入参
INSERT INTO tbl_user
(name, addr, age, score, fav)
VALUES
('aaa','aaa_addr',10, 23,'aaa_fav_new'),
('bbb','ccc_addr',10, 23,'bbb_fav_new'),
('ddd','ddd_addr',10, 22,'ccc_fav'),
('eee','eee_addr',10, 22,'ddd_fav')
ON conflict(name,addr,age) DO
UPDATE set score=excluded.score, fav=excluded.fav;
MYSQL:
1、创建表
create table tbl_user(
id int PRIMARY KEY AUTO_INCREMENT,
name varchar(256),
addr varchar(256),
age int,
score int,
fav varchar(256)
);
2、创建唯一约束
alter table tbl_user add constraint name_add_age_unique unique(name,addr,age);
3、首先插入两条数据
INSERT INTO tbl_user
(name, addr, age, score, fav)
VALUES
('aaa','aaa_addr',10,22,'aaa_fav'),
('bbb','ccc_addr',10,22,'bbb_fav');
4、直接INSERT INTO,会直接报唯一键冲突,插入失败
INSERT INTO tbl_user
(name, addr, age, score, fav)
VALUES
('aaa','aaa_addr',10, 23,'aaa_fav_new'),
('bbb','ccc_addr',10, 23,'bbb_fav_new'),
('ddd','ddd_addr',10, 22,'ccc_fav'),
('eee','eee_addr',10, 22,'ddd_fav')
5、采用UPDATE_INSERT方式,插入成功,并且对冲突列执行指定更新操作
语法说明:
1、ON DUPLICATE KEY,用于识别唯一键冲突操作
2、CALUES(列名), 用于获取插入的时入参
INSERT INTO tbl_user
(name, addr, age, score, fav)
VALUES
('aaa','aaa_addr',10, 23,'aaa_fav_new'),
('bbb','ccc_addr',10, 23,'bbb_fav_new'),
('ddd','ddd_addr',10, 22,'ccc_fav'),
('eee','eee_addr',10, 22,'ddd_fav')
ON DUPLICATE KEY
UPDATE score=VALUES(score), fav=VALUES(fav);