Mysql 實(shí)現(xiàn)批量插入對(duì)已存在數(shù)據(jù)忽略/更新
一. 表的準(zhǔn)備
CREATE TABLE `demo` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
`name` varchar(10) DEFAULT NULL COMMENT '姓名',
`age` int DEFAULT NULL COMMENT '年齡',
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='demo表';
二. 實(shí)現(xiàn)
2.1 實(shí)現(xiàn)原理
對(duì)已存在的數(shù)據(jù)進(jìn)行忽略/更新
,需要唯一索引/主鍵。
唯一索引可為多個(gè)字段的聯(lián)合索引,比如根據(jù)我提供的sql中,我需要``name+
age`不重復(fù),則可把這2個(gè)字段聯(lián)合創(chuàng)建為唯一索引
創(chuàng)建聯(lián)合唯一索引的sql
alter table table_name add unique index unique_index_name (field1,field2...);
-
批量插入對(duì)已存在數(shù)據(jù)忽略
insert ignore table_name (field1, field2...) values (value1, value2...),(value1, value2...);
-
批量插入對(duì)已存在數(shù)據(jù)更新
replace into table_name (field1, field2...) values (value1, value2...),(value1, value2...);
筆者這里只舉例第一種情況的demo
對(duì)已存在數(shù)據(jù)更新情況,讀者自行練習(xí)
2.2 批量插入對(duì)已存在數(shù)據(jù)忽略
現(xiàn)在我們把name
+age
創(chuàng)建聯(lián)合唯一索引
alter table demo add unique index unique_name_age (name,age);
新增索引后,我們開始批量插入數(shù)據(jù)
這里我們先制造2條數(shù)據(jù),來(lái)判斷我們批量插入是否能對(duì)已存在的數(shù)據(jù)進(jìn)行忽略。
INSERT INTO `demo` (`id`, `name`, `age`) VALUES (1, '張三', 10);
INSERT INTO `demo` (`id`, `name`, `age`) VALUES (2, '李四', 10);
我們開始批量插入,對(duì)已存在數(shù)據(jù)進(jìn)行忽略
insert ignore demo values (null, '張三',10),(null, '小黑',11);
運(yùn)行過(guò)程
運(yùn)行結(jié)果展示文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-551955.html
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-551955.html
到了這里,關(guān)于Mysql 實(shí)現(xiàn)批量插入對(duì)已存在數(shù)據(jù)忽略或更新的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!