共計(jì) 2045 個(gè)字符,預(yù)計(jì)需要花費(fèi) 6 分鐘才能閱讀完成。
自動(dòng)寫代碼機(jī)器人,免費(fèi)開(kāi)通
mysql 中怎么實(shí)現(xiàn)循環(huán)批量插入,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
數(shù)據(jù)結(jié)構(gòu)
尋思著分頁(yè)時(shí)標(biāo)準(zhǔn)列分主鍵列、索引列、普通列 3 種場(chǎng)景,所以,測(cè)試表需要包含這 3 種場(chǎng)景,建表語(yǔ)法如下:
drop table if exists `test`.`t_model`;
Create table `test`.`t_model`(
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 自增主鍵 ,
`uid` bigint COMMENT 業(yè)務(wù)主鍵 ,
`modelid` varchar(50) COMMENT 字符主鍵 ,
`modelname` varchar(50) COMMENT 名稱 ,
`desc` varchar(50) COMMENT 描述 ,
primary key (`id`),
UNIQUE index `uid_unique` (`uid`),
key `modelid_index` (`modelid`) USING BTREE
) ENGINE=InnoDB charset=utf8 collate=utf8_bin;
為了方便操作,插入操作使用存儲(chǔ)過(guò)程通過(guò) while 循環(huán)插入有序數(shù)據(jù),未驗(yàn)證其他操作方式或循環(huán)方式的性能。
執(zhí)行過(guò)程
1、使用最簡(jiǎn)單的方式直接循環(huán)單條插入 1W 條,語(yǔ)法如下:
drop procedure if exists my_procedure;
delimiter //
create procedure my_procedure()
begin
DECLARE n int DEFAULT 1;
WHILE n 10001 DO
insert into t_model (uid,modelid,modelname,`desc`) value (n,CONCAT( id20170831 ,n),CONCAT(name ,n), desc
set n = n + 1;
END WHILE;
delimiter ;
插入 1W 條數(shù)據(jù),執(zhí)行時(shí)間大概在 6m7s,按照這個(gè)速度,要插入 1000W 級(jí)數(shù)據(jù),估計(jì)要跑幾天。
2、于是,構(gòu)思加個(gè)事務(wù)提交,是否能加快點(diǎn)性能呢?測(cè)試每 1000 條就 commit 一下,語(yǔ)法如下:
delimiter //
create procedure u_head_and_low_pro()
begin
DECLARE n int DEFAULT 17541;
WHILE n 10001 DO
insert into t_model (uid,modelid,modelname,`desc`) value (n,CONCAT( id20170831 ,n),CONCAT(name ,n), desc
set n = n + 1;
if n % 1000 = 0
then
commit;
end if;
END WHILE;
delimiter ;
執(zhí)行時(shí)間 6 min 16 sec,與不加 commit 執(zhí)行差別不大,看來(lái),這種方式做批量插入,性能是很低的。
3、使用存儲(chǔ)過(guò)程生成批量插入語(yǔ)句執(zhí)行批量插入插入 1W 條,語(yǔ)法如下:
drop procedure IF EXISTS u_head_and_low_pro;
delimiter $$
create procedure u_head_and_low_pro()
begin
DECLARE n int DEFAULT 1;
set @exesql = insert into t_model (uid,modelid,modelname,`desc`) values
set @exedata =
WHILE n 10001 DO
set @exedata = concat(@exedata, ( ,n, , , id20170831 ,n, , , name ,n, , , desc ,)
if n % 1000 = 0
then
set @exesql = concat(@exesql,@exedata,
prepare stmt from @exesql;
execute stmt;
DEALLOCATE prepare stmt;
commit;
set @exesql = insert into t_model (uid,modelid,modelname,`desc`) values
set @exedata =
else
set @exedata = concat(@exedata, ,
end if;
set n = n + 1;
END WHILE;
end;$$
delimiter ;
關(guān)于 mysql 中怎么實(shí)現(xiàn)循環(huán)批量插入問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注丸趣 TV 行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
向 AI 問(wèn)一下細(xì)節(jié)