有时候需我们要组合几张表的数据,在存储过程中,经过比较复杂的运算获取结果直接输出给调用方,比如符合条件的几张表的某些字段的组合计算,mysql临时表可以解决这个问题.

所谓临时表:只有在当前连接情况下, TEMPORARY 表才是可见的。当连接关闭时, TEMPORARY 表被自动取消。必须拥有 create temporary table 权限,才能创建临时表。可以通过指定 engine = memory; 来指定创建内存临时表。

drop table if exists  pre_person;
create table `person` (
`id` int(11)primary key NOT NULL DEFAULT '',
`age` int(11) DEFAULT NULL,
`name` varchar(25) not null
) engine=innodb default charset=utf8;
insert into person values(1,1,'张三'),(2,2,'李四'),(3,3,'王五'),(4,4,'赵六'),(5,5,'许仙');

临时表支持主键、索引指定。在连接非临时表查询可以利用指定主键或索引来提升性能。比如这里我用存储过程语句及游标和临时表综合实例:

drop procedure if exists sp_test; -- 判断存储过程函数是否存在如果是删除
delimiter ;;
create procedure sp_test()
begin
create temporary table if not exists tmp -- 如果表已存在,则使用关键词 if not exists 可以防止发生错误
(
id int(11) ,
name varchar(10),
age int(3)
) engine = memory;
begin
declare ids int; -- 接受查询变量
declare names varchar(10); -- 接受查询变量
declare done int default false; -- 跳出标识
declare ages int(3); -- 接受查询变量
declare cur cursor for select id from person; -- 声明游标
declare continue handler for not FOUND set done = true; -- 循环结束设置跳出标识
open cur; -- 开始游标
LOOP_LABLE:loop -- 循环
FETCH cur INTO ids;
select name into names from person where id=ids;
select age into ages from person where id=ids;
insert into tmp(id,name,age) value(ids,names,ages);
if done THEN -- 判断是否继续循环如果done等于true离开循环
LEAVE LOOP_LABLE; -- 离开循环
END IF;
end LOOP; -- 结束循环
CLOSE cur; -- 关闭游标
select * from tmp; -- 查询临时表
end;
truncate TABLE tmp; -- 使用 truncate TABLE 的方式来提升性能
end;
;;
delimiter ;;

然后执行存储过程:

call sp_test();

??部分是字符编码问题...大家可以改下字符集(我这里就不再修改了。)

最新文章

  1. NPM使用前设置和升级
  2. [UCSD白板题] Maximize the Value of an Arithmetic Expression
  3. 哟西,CLOUDSTACK第一步,搞定
  4. Time_wait问题小结
  5. msdn我告诉你
  6. 聊聊Node.js 独立日漏洞
  7. Jenkins: 配置信息变更历史
  8. Docker----与Asp.net core 的完美结合,在docker容器中创建Asp.Net Core 项目
  9. C#访问gsoap的服务
  10. 【Java并发编程】14、Thread,线程说明
  11. 6种innodb数据字典恢复方法
  12. opencv删除轮廓
  13. 信息安全技术PGP实验 20155205 20155218
  14. 课程三(Structuring Machine Learning Projects),第一周(ML strategy(1)) —— 1.Machine learning Flight simulator:Bird recognition in the city of Peacetopia (case study)
  15. C#/.NET 学习之路——从入门到放弃
  16. (笔记)Linux延时及时间函数总结
  17. 高校区LAN局域网校内网组建实践经验
  18. MySQL5.7 主从复制配置
  19. STL标准库-迭代器适配器
  20. JS的__proto__与prototype

热门文章

  1. python模块:datetime
  2. OpenCV2.4.10 + VS2010开发环境配置
  3. 可遇不可求的Question之flash的socket连接安全策略文件篇
  4. 使用百度地图实现详细地址自动补全(补全bug''事件只能绑定到一个上的问题')
  5. Vuejs——(13)组件——杂项
  6. 9.10 翻译系列:EF数据注解特性之StringLength【EF 6 Code-First系列】
  7. 背水一战 Windows 10 (87) - 文件系统: 获取文件的属性, 修改文件的属性, 获取文件的缩略图
  8. while循环 格式化输出 密码本 编码的初识
  9. Linux源码编译安装程序
  10. javascript Navigator对象属性和方法