MySQL迴圈插入千萬級資料
阿新 • • 發佈:2020-09-21
1、建立測試表
CREATE TABLE `mysql_genarate` ( `id` int(11) NOT NULL AUTO_INCREMENT,`uuid` varchar(50) DEFAULT NULL,PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5999001 DEFAULT CHARSET=utf8;
2、建立一個迴圈插入的儲存過程
CREATE DEFINER=`root`@`localhost` PROCEDURE `test_two1`( ) BEGIN DECLARE i INT DEFAULT 0; WHILE i < 3000 DO INSERT INTO mysql_genarate ( uuid ) VALUES( UUID( ) ); SET i = i + 1; END WHILE; END
呼叫測試call test_two1()
,測試10000條資料耗時幾分鐘,如果是千萬級資料,這個速度將無法忍受。
3、優化儲存過程
使用批量插入的sql語句
CREATE DEFINER=`root`@`localhost` PROCEDURE `insertPro`( IN sum INT ) BEGIN DECLARE count INT DEFAULT 0; DECLARE i INT DEFAULT 0; SET @exesql = concat( "insert into mysql_genarate(uuid) values" ); SET @exedata = ""; SET count = 0; SET i = 0; WHILE count < sum DO SET @exedata = concat( @exedata,",(UUID())" ); SET count = count + 1; SET i = i + 1; IF i % 1000 = 0 THEN SET @exedata = SUBSTRING( @exedata,2 ); SET @exesql = concat( "insert into mysql_genarate(uuid) values ",@exedata ); PREPARE stmt FROM @exesql; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @exedata = ""; END IF; END WHILE; IF length( @exedata ) > 0 THEN SET @exedata = SUBSTRING( @exedata,2 ); SET @exesql = concat( "insert into mysql_genarate(uuid) values ",@exedata ); PREPARE stmt FROM @exesql; EXECUTE stmt; DEALLOCATE PREPARE stmt; END IF; END
呼叫 call insertPro(10000) ,耗時零點幾秒,這個速度可以接受。
以上就是MySQL迴圈插入千萬級資料的詳細內容,更多關於MySQL迴圈插入的資料請關注我們其它相關文章!