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编程》
例如:生成一连串连续的数值。
表:
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编程中的6个实用技巧
- MySQL 编程的6个重要的技巧
- MySQL编程中的6个实用技巧
- MySQL 编程的6个重要的技巧
- PHP Mysql编程之高级技巧
- MySQL编程中的6个重要的实用技巧
- widnows游戏编程大师技巧 Draw_Line 的学习
- 提高MySQL性能的7个技巧
- FPGA设计中的编程技巧
- C语言编程技巧-signal(信号机制)
- Python:Mysql编程(基础操作命令)
- PHP与MySQL开发的8个技巧小结
- 程序员编程面试取胜的8个技巧
- java学习笔记(一)--编程规范和技巧总结
- UNIX 编程技巧——如何 hook 一个共享库
- (NEON实例一)ARM处理器NEON编程及优化技巧——数据加载和存储
- 读书笔记-MySQL存储过程编程教程-触发器
- asp.net向mysql插入数据,中文编程问号解决方案
- mysql使用技巧