您的位置:首页 > 数据库 > MySQL

MySQL 编程技巧(一)

2012-08-12 19:14 218 查看
工作中我们可能会建立类似的辅助表,并填充一定量的数据来完成工作。

例如:生成一连串连续的数值。

表:

create table nums (a int unsigned not null primary key)engine=innodb;

一般的做法是建立一个存储过程:

delimiter $$

create procedure pCreateNums (cnt int unsigned)

begin

declare s int unsigned default 1;

truncate table Nums;

while s <= cnt do

begin

insert into Nums select s;

set s=s+1;

end;

end while;

end$$

delimiter ;

执行的时候: call pCreateNums(200000); 此时这个程序insert 插入的次数是 2W次。

下面看看优化后的存储过程:

delimiter $$

create procedure pFastCreateNums (cnt int unsigned)

begin

declare s int unsigned default 1;

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 $$

DELIMITER ;

执行: call pFastCreateNums(200000); 该过程会先把1插入到表中,然后当 s*2<=cnt的成立的时候执行循环,每次迭代的时候会把当前所有行的值加上s再插入到表中。 即: 先插入1 , 然后是 2, (3,4), (5,6,7,8),(9,10,11,12,13,14,15,16)以此类推。

该过程执行的时候insert减少,只执行了17操作,最大值是2**17=131072,不过这个数已经够我们用啦。

参考:《MySQL技术内幕-SQL编程》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  MySQL 技巧 存储过程