ITPub博客

首页 > 数据库 > MySQL > MySQL 数字辅助表

MySQL 数字辅助表

翻译 MySQL 作者:神谕丶 时间:2014-08-10 00:03:10 0 删除 编辑
首先创建数字辅助表


  1. create table nums(
  2. a int unsigned primary key);



创建存储过程,将数字插入nums中



  1. create procedure pCreateNums (cnt int unsigned)
  2. begin
  3.     declare a int unsigned default 1;
  4.     truncate table nums;
  5.     while a<=cnt do
  6.         begin
  7.             insert into nums select a;
  8.             set a=a+1;
  9.         end;
  10.     end while;
  11. end;


然后插入50,000个数字


  1. call pCreateNums (50000);



但是此存储过程效率太慢,主要开销在于insert语句被执行了50,000次


优化方法:


  1. create procedure pFastCreateNums (cnt int unsigned)
  2. begin
  3.     declare s int unsigned default 1;
  4.     truncate table nums;
  5.     insert into nums select s;
  6.     while s*2<=cnt do
  7.         begin
  8.             insert into nums select a+s from nums;
  9.             set s=s*2;
  10.         end;
  11.     end while;
  12. end;


若执行

  1. call pFastCreateNums (50000);


最终插入的数值虽并非50,000个(大于50,000),但极大减少了insert次数,这将大大提升效率。
使用的时候,可以通过where来限制。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29773961/viewspace-1248559/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
微信公众号:神谕的暗影长廊

注册时间:2014-07-28

  • 博文量
    161
  • 访问量
    1195299