首先创建数字辅助表
-
create table nums(
-
a int unsigned primary key);
创建存储过程,将数字插入nums中
-
create procedure pCreateNums (cnt int unsigned)
-
begin
-
declare a int unsigned default 1;
-
truncate table nums;
-
while a<=cnt do
-
begin
-
insert into nums select a;
-
set a=a+1;
-
end;
-
end while;
-
end;
然后插入50,000个数字
-
call pCreateNums (50000);
但是此存储过程效率太慢,主要开销在于insert语句被执行了50,000次
优化方法:
-
create procedure pFastCreateNums (cnt int unsigned)
-
begin
-
declare s int unsigned default 1;
-
truncate table nums;
-
insert into nums select s;
-
while s*2<=cnt do
-
begin
-
insert into nums select a+s from nums;
-
set s=s*2;
-
end;
-
end while;
-
end;
若执行
-
call pFastCreateNums (50000);
最终插入的数值虽并非50,000个(大于50,000),但极大减少了insert次数,这将大大提升效率。
使用的时候,可以通过where来限制。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29773961/viewspace-1248559/
,如需转载,请注明出处,否则将追究法律责任。