create table tbl_user(
id serial PRIMARY KEY,
name varchar(256),
addr varchar(256),
age int,
score int,
fav varchar(256)
);
alter table tbl_user add constraint name_add_age_unique unique(name,addr,age);
INSERT INTO tbl_user
(name, addr, age, score, fav)
VALUES
('aaa','aaa_addr',10,22,'aaa_fav'),
('bbb','ccc_addr',10,22,'bbb_fav');
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');
语法说明:
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;
create table tbl_user(
id int PRIMARY KEY AUTO_INCREMENT,
name varchar(256),
addr varchar(256),
age int,
score int,
fav varchar(256)
);
alter table tbl_user add constraint name_add_age_unique unique(name,addr,age);
INSERT INTO tbl_user
(name, addr, age, score, fav)
VALUES
('aaa','aaa_addr',10,22,'aaa_fav'),
('bbb','ccc_addr',10,22,'bbb_fav');
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')
语法说明:
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);