MySQL TIPS 5 ã¹ãã¢ãããã·ã¼ã¸ã£ã§æå®ããæ°ã®ããã¼ãã¼ã¿ãç¨æãã2 (失æç·¨)
以åã®ã¨ã³ããªã¼ã§ä½ã£ãinsert_generate_seriesãè¤æ°INSERT,è¤æ°ã«ã©ã ã§çæãã¼ã¿ã使ç¨å¯è½ã«ãã¦ã¿ã
DROP PROCEDURE insert_generate_series; delimiter // CREATE PROCEDURE insert_generate_series( IN target VARCHAR(255) , -- insert対象ã®ãã¼ãã«ãã«ã©ã åãæå® IN value VARCHAR(255) , -- valuesãè¨è¿° @numãgenerate_seriesã§çæãããå¤ã«ãªã IN start_num INT , -- éå§å¤ IN end_num INT , -- çµäºå¤ IN step INT -- å¢å ) begin set @num:= start_num; set @sql:= concat('INSERT INTO ',target,' VALUES '); while @num <= end_num do set @sql:=concat(@sql,' ( ', replace(value,'@num',@num) , ' )'); if @num <> end_num then set @sql:=concat(@sql,','); end if; set @num:=@num + step; end while; prepare stmt from @sql; execute stmt; end; // delimiter ; call insert_generate_series('user(user_name)','concat(md5(@num),@num)',1,100000,1);
Query OK, 100000 rows affected (9 min 43.20 sec);
ã¡ãããã¾ããªãã ãã®é ãã¯....ãçæãããinsertæãå®è¡ããã®ã¯1ç§æªæºã§ãããã©ãããINSERTæãçæããéã®concatã«æéãæãã£ã¦ããããã§ãã
- åé·ã«ãªã£ã¦ãã¾ããã«ã¼ãä¸ã®IFæãåãé¤ãã¦ã¿ã
DROP PROCEDURE insert_generate_series; delimiter // CREATE PROCEDURE insert_generate_series( IN target VARCHAR(255) , -- insert対象ã®ãã¼ãã«ãã«ã©ã åãæå® IN value VARCHAR(255) , -- valuesãè¨è¿° @numãgenerate_seriesã§çæãããå¤ã«ãªã IN start_num INT , -- éå§å¤ IN end_num INT , -- çµäºå¤ IN step INT -- å¢å ) begin set @num:= start_num; set @sql:= concat('INSERT INTO ',target,' VALUES '); while @num < end_num do set @sql:=concat(@sql,' ( ', replace(value,'@num',@num) , ' ),'); set @num:=@num + step; end while; set @sql:=concat(@sql,' ( ', replace(value,'@num',@num) , ' )'); prepare stmt from @sql; execute stmt; end; // delimiter ; call insert_generate_series('user(user_name)','concat(md5(@num),@num)',1,100000,1);
Query OK, 100000 rows affected (4 min 25.48 sec)
ãªãã¨2åï¼ï¼ãé©ãã®é度ã«ã
DROP PROCEDURE insert_generate_series; delimiter // CREATE PROCEDURE insert_generate_series( IN target VARCHAR(255) , -- insert対象ã®ãã¼ãã«ãã«ã©ã åãæå® IN value VARCHAR(255) , -- valuesãè¨è¿° @numãgenerate_seriesã§çæãããå¤ã«ãªã IN start_num INT , -- éå§å¤ IN end_num INT , -- çµäºå¤ IN step INT -- å¢å ) begin set @num:= start_num; set @sql:= concat('INSERT INTO ',target,' VALUES '); while @num < end_num do set @sql:=concat(@sql,' ( ', replace(value,'@num',@num) , ' ),'); if @num%100=0 then select @num; end if; set @num:=@num + step; end while; set @sql:=concat(@sql,' ( ', replace(value,'@num',@num) , ' )'); prepare stmt from @sql; execute stmt; end; // delimiter ; call insert_generate_series('user(user_name)','concat(md5(@num),@num)',1,100000,1);
concatæã®ã¦ã¼ã¶å¤æ°ã®ãããã¡ã大ãããªãã»ã©ã«é ããªã£ã¦ããã®ãããããIFæã®æ°ãæ¸ã£ãããæ©ããªã£ãã®ã§ã¯ãªãconcatã®å®è¡åæ°ãæ¸ã£ãã®ã§æ©ããªã£ããããã