在mysql中,临时表指的是临时使用的一张表,是用于存储一些中间结果集的表;临时表只在当前连接可见,当关闭连接时,mysql会自动删除表并释放所有空间。
本教程操作环境:windows7系统、mysql8版本、dell g3电脑。
临时表,是临时使用的一张表。
临时表是mysql用于存储一些中间结果集的表,临时表只在当前连接可见,当关闭连接时,mysql会自动删除表并释放所有空间。
使用其他mysql客户端程序连接mysql数据库服务器来创建临时表,那么只有在关闭客户端程序时才会销毁临时表,当然也可以手动删除。
注:临时表在mysql 3.23版本中添加,如果你的mysql版本低于 3.23版本就无法使用mysql的临时表。不过现在一般很少有再使用这么低版本的mysql数据库服务了
mysql中的两种临时表
外部临时表
通过create temporary table 创建的临时表,这种临时表称为外部临时表。这种临时表只对当前用户可见,当前会话结束的时候,该临时表会自动关闭。这种临时表的命名与非临时表可以同名(同名后非临时表将对当前会话不可见,直到临时表被删除)。
内部临时表
内部临时表是一种特殊轻量级的临时表,用来进行性能优化。这种临时表会被mysql自动创建并用来存储某些操作的中间结果。这些操作可能包括在优化阶段或者执行阶段。这种内部表对用户来说是不可见的,但是通过explain或者show status可以查看mysql是否使用了内部临时表用来帮助完成某个操作。内部临时表在sql语句的优化过程中扮演着非常重要的角色, mysql中的很多操作都要依赖于内部临时表来进行优化。但是使用内部临时表需要创建表以及中间数据的存取代价,所以用户在写sql语句的时候应该尽量的去避免使用临时表。
内部临时表有两种类型:
一种是heap临时表,这种临时表的所有数据都会存在内存中,对于这种表的操作不需要io操作。
另一种是ondisk临时表,顾名思义,这种临时表会将数据存储在磁盘上。ondisk临时表用来处理中间结果比较大的操作。
如果heap临时表存储的数据大于max_heap_table_size,heap临时表将会被自动转换成ondisk临时表。
ondisk临时表在5.7中可以通过internal_tmp_disk_storage_engine系统变量选择使用myisam引擎或者innodb引擎。
外部临时表的常见用法
外部临时表是通过create temporary table及drop table来操作的,但是show tables命令显示数据表列表时,你将无法看到自己创建的临时表的。并且在退出当前会话后,临时表就会被自动销毁。当然也可以手动(drop table)销毁。
1、引擎类型:只能是:memory(heap)、myisam、merge、innodb ,不支持mysql cluster(簇)。
2、外部临时表使用时注意几点:
1)、自己所用的数据库账号要有建立临时表的权限;
2)、在同一条sql中,不能关联2次相同的临时表,不然,就会报如下错误;
mysql> select * from temp_table, temp_table as t2;error 1137: can't reopen table: 'temp_table'
3)、临时表在建立连接时可见,关闭时会清除空间,删除临时表;
4)、show tables 不会列出临时表;
5)、不能使用rename重命名临时表。但是,你可以alter table代替:只能使用alter table old_tp_table_name rename new_tp_table_name;
6)、影响使用replication功能;
7)、如果你为一个表声明了别名,当你指向这个表的时候,就必须使用这个别名。见《mysql 多表关联更新及删除》
示例:
mysql> create temporary table salessummary ( -> product_name varchar(50) not null -> , total_sales decimal(12,2) not null default 0.00 -> , avg_unit_price decimal(7,2) not null default 0.00 -> , total_units_sold int unsigned not null default 0);query ok, 0 rows affected (0.00 sec)mysql> insert into salessummary -> (product_name, total_sales, avg_unit_price, total_units_sold) -> values -> ('cucumber', 100.25, 90, 2);mysql> select * from salessummary;+--------------+-------------+----------------+------------------+| product_name | total_sales | avg_unit_price | total_units_sold |+--------------+-------------+----------------+------------------+| cucumber | 100.25 | 90.00 | 2 |+--------------+-------------+----------------+------------------+1 row in set (0.00 sec)mysql> drop table salessummary; mysql> select * from salessummary; error 1146: table 'runoob.salessummary' doesn't exist
3、mybatis中临时表操作
<update id="createtemptable"> create temporary table if not exists temp select * from settlement_temp where settle_date=#{settledate} and length(operator) in(16,32) and pay_status in ('01','06') order by settle_date,merchant_no </update>
<!-- 4、删除临时表 --> <update id="droptemptable"> drop temporary table if exists settlement_temp; </update>
内部临时表的常见用法
如果用户在书写sql语句的时候能够尽量少的使用内部临时表进行查询优化,将有效的提高查询执行的效率。
首先我们定义一个表t1,
create table t1( a int, b int); insert into t1 values(1,2),(3,4);
下面所有的操作都是基于表t1进行举例的。
在sql语句中使用sql_buffer_result hint
sql_buffer_result主要用来让mysql尽早的释放表上的锁。因为如果数据量很大的话,需要较长时间将数据发送到客户端,通过将数据缓冲到临时表中可以有效的减少读锁对表的占用时间。sql_buffer_result见《mysql查询优化之三:查询优化器提示(hint)》
例如:
mysql> explain format=json select sql_buffer_result * from t1; explain { "query_block": { "select_id": 1, "cost_info": { "query_cost": "2.00" }, "buffer_result": { "using_temporary_table": true, "table": { "table_name": "t1", "access_type": "all", ...
如果sql语句中包含了derived_table。
在5.7中,由于采用了新的优化方式,我们需要使用 set optimizer_switch=’derived_merge=off’来禁止derived table合并到外层的query中。
例如:
mysql> explain format=json select * from (select * from t1) as tt; explain { "query_block": { "select_id": 1, "cost_info": { "query_cost": "2.40" }, "table": { "table_name": "tt", "access_type": "all", ... "materialized_from_subquery": { "using_temporary_table": true, ...
如果我们查询系统表的话,系统表的数据将被存储到内部临时表中。
我们当前不能使用explain来查看是否读取系统表数据需要利用到内部临时表,但是可以通过show status来查看是否利用到了内部临时表。
例如:
mysql> select * from information_schema.character_sets;mysql> show status like 'create%';
如果distinct语句没有被优化掉,即distinct语句被优化转换为group by操作或者利用unique index消除distinct, 内部临时表将会被使用。
mysql> explain format=json select distinct a from t1; explain { { "query_block": { "select_id": 1, "cost_info": { "query_cost": "1.60" }, "duplicates_removal": { "using_temporary_table": true, ...
如果查询带有order by语句,并且不能被优化掉。下面几种情况会利用到内部临时表缓存中间数据,然后对中间数据进行排序。
1)如果连接表使用bnl(batched nestloop)/bka(batched key access)
例如:
1))bnl默认是打开的
mysql> explain format=json select * from t1, t1 as t2 order by t1.a;explain{ "query_block": { "select_id": 1, "cost_info": { "query_cost": "22.00" }, "ordering_operation": { "using_temporary_table": true, ...
2))关掉bnl后,order by将直接使用filesort。
mysql> set optimizer_switch='block_nested_loop=off';query ok, 0 rows affected (0.00 sec)mysql> explain format=json select * from t1, t1 as t2 order by t1.a;explain{ "query_block": { "select_id": 1, "cost_info": { "query_cost": "25.00" }, "ordering_operation": { "using_filesort": true, ...
2)order by的列不属于执行计划中第一个连接表的列。
例如:
mysql> explain format=json select * from t as t1, t as t2 order by t2.a;explain{ "query_block": { "select_id": 1, "cost_info": { "query_cost": "25.00" }, "ordering_operation": { "using_temporary_table": true, ...
3)如果order by的表达式是个复杂表达式。
那么什么样的order by表达式,mysql认为是复杂表达式呢?
1))如果排序表达式是sp或者udf。
例如:
drop function if exists func1;delimiter |create function func1(x int)returns int deterministicbegindeclare z1, z2 int;set z1 = x;set z2 = z1+2;return z2;end|delimiter ;explain format=json select * from t1 order by func1(a);{ "query_block": { "select_id": 1, "cost_info": { "query_cost": "2.20" }, "ordering_operation": { "using_temporary_table": true, ...
2))order by的列包含聚集函数
为了简化执行计划,我们利用index来优化group by语句。
例如:
create index idx1 on t1(a); explain format=json select a from t1 group by a order by sum(a); | { "query_block": { "select_id": 1, "cost_info": { "query_cost": "1.20" }, "ordering_operation": { "using_temporary_table": true, "using_filesort": true, "grouping_operation": { "using_filesort": false, ... drop index idx1 on t1;
3))order by的列中包含有scalar subquery,当然该scalar subquery没有被优化掉。
例如:
explain format=json select (select rand() from t1 limit 1) as a from t1 order by a; | { "query_block": { "select_id": 1, "cost_info": { "query_cost": "1.20" }, "ordering_operation": { "using_temporary_table": true, "using_filesort": true, ...
4) 如果查询既带有order by同时也有group by语句,但是两个语句使用的列不相同。
注意: 如果是5.7,我们需要将sql_mode设置为非only_full_group_by模式,否则会报错。
同样为了简化执行计划,我们利用index来优化group by语句。
例如:
set sql_mode='';create index idx1 on t1(b);explain format=json select t1.a from t1 group by t1.b order by 1;| { "query_block": { "select_id": 1, "cost_info": { "query_cost": "1.40" }, "ordering_operation": { "using_temporary_table": true, "using_filesort": true, "grouping_operation": { "using_filesort": false, ...drop index idx1 on t1;
如果查询带有group by语句,并且不能被优化掉。下面几种情况会利用到内部临时表缓存中间数据,然后对中间数据进行group by。
1)如果连接表使用bnl(batched nestloop)/bka(batched key access)。
例如:
explain format=json select t2.a from t1, t1 as t2 group by t1.a; | { "query_block": { "select_id": 1, "cost_info": { "query_cost": "8.20" }, "grouping_operation": { "using_temporary_table": true, "using_filesort": true, "cost_info": { "sort_cost": "4.00" ...
2) 如果group by的列不属于执行计划中的第一个连接表。
例如:
explain format=json select t2.a from t1, t1 as t2 group by t2.a; | { "query_block": { "select_id": 1, "cost_info": { "query_cost": "8.20" }, "grouping_operation": { "using_temporary_table": true, "using_filesort": true, "nested_loop": [ ...
3) 如果group by语句使用的列与order by语句使用的列不同。
例如:
set sql_mode=''; explain format=json select t1.a from t1 group by t1.b order by t1.a; | { "query_block": { "select_id": 1, "cost_info": { "query_cost": "1.40" }, "ordering_operation": { "using_filesort": true, "grouping_operation": { "using_temporary_table": true, "using_filesort": false, ...
4) 如果group by带有rollup并且是基于多表外连接。
例如:
explain format=json select sum(t1.a) from t1 left join t1 as t2 on true group by t1.a with rollup; | { "query_block": { "select_id": 1, "cost_info": { "query_cost": "7.20" }, "grouping_operation": { "using_temporary_table": true, "using_filesort": true, "cost_info": { "sort_cost": "4.00" }, ...
5) 如果group by语句使用的列来自于scalar subquery,并且没有被优化掉。
例如:
explain format=json select (select avg(a) from t1) as a from t1 group by a;| {"query_block": {"select_id": 1,"cost_info": { "query_cost": "3.40"},"grouping_operation": { "using_temporary_table": true, "using_filesort": true, "cost_info": {"sort_cost": "2.00" },...
in表达式转换为semi-join进行优化
1) 如果semi-join执行方式为materialization
例如:
set optimizer_switch='firstmatch=off,duplicateweedout=off';explain format=json select * from t1 where a in (select b from t1);| {"query_block": {"select_id": 1,"cost_info": { "query_cost": "5.60"},"nested_loop": [ {"rows_examined_per_scan": 1, "materialized_from_subquery": {"using_temporary_table": true,"query_block": { "table": {"table_name": "t1","access_type": "all",...
2) 如果semi-join执行方式为duplicate weedout
例如:
set optimizer_switch='firstmatch=off';explain format=json select * from t1 where a in (select b from t1);| {"query_block": {"select_id": 1,"cost_info": { "query_cost": "4.80"},"duplicates_removal": { "using_temporary_table": true, "nested_loop": [{...
如果查询语句带有union,mysql将利用内部临时表帮助union操作消除重复。
例如:
explain format=json select * from t1 union select * from t1;| {"query_block": {"union_result": { "using_temporary_table": true, "table_name": "<union1,2>",...
如果查询语句使用多表更新。
这里explain不能看到内部临时表被利用,所以需要查看status。
例如:
update t1, t1 as t2 set t1.a=3;show status like 'create%';
如果聚集函数中包含如下函数,内部临时表也会被利用。
1) count(distinct *)例如:explain format=json select count(distinct a) from t1;2) group_concat例如:explain format=json select group_concat(b) from t1;
总之,上面列出了10种情况,mysql将利用内部临时表进行中间结果缓存,如果数据量比较大的话,内部临时表将会把数据存储在磁盘上,这样显然会对性能有所影响。为了尽可能的减少性能损失,我们需要尽量避免上述情况的出现。
mysql在以下几种情况会创建临时表:
1、union查询;2、用到temptable算法或者是union查询中的视图;3、order by和group by的子句不一样时;4、表连接中,order by的列不是驱动表中的;5、distinct查询并且加上order by时;6、sql中用到sql_small_result选项时;7、from中的子查询;8、子查询或者semi-join时创建的表;
explain 查看执行计划结果的 extra 列中,如果包含 using temporary 就表示会用到临时表。
当然了,如果临时表中需要存储的数据量超过了上限( tmp-table-size 或 max-heap-table-size 中取其大者),这时候就需要生成基于磁盘的临时表了。
在以下几种情况下,会创建磁盘临时表:
1、数据表中包含blob/text列;2、在 group by 或者 dstinct 的列中有超过 512字符 的字符类型列(或者超过 512字节的 二进制类型列,在5.6.15之前只管是否超过512字节);3、在select、union、union all查询中,存在最大长度超过512的列(对于字符串类型是512个字符,对于二进制类型则是512字节);4、执行show columns/fields、describe等sql命令,因为它们的执行结果用到了blob列类型。
从5.7.5开始,新增一个系统选项 internal_tmp_disk_storage_engine 可定义磁盘临时表的引擎类型为 innodb,而在这以前,只能使用 myisam。而在5.6.3以后新增的系统选项 default_tmp_storage_engine 是控制 create temporary table 创建的临时表的引擎类型,在以前默认是memory,不要把这二者混淆了。
见下例:
mysql> set default_tmp_storage_engine = "innodb";-rw-rw---- 1 mysql mysql 8558 jul 7 15:22 #sql4b0e_10_0.frm -- innodb引擎的临时表-rw-rw---- 1 mysql mysql 98304 jul 7 15:22 #sql4b0e_10_0.ibd-rw-rw---- 1 mysql mysql 8558 jul 7 15:25 #sql4b0e_10_2.frmmysql> set default_tmp_storage_engine = "myisam";-rw-rw---- 1 mysql mysql 0 jul 7 15:25 #sql4b0e_10_2.myd -- myisam引擎的临时表-rw-rw---- 1 mysql mysql 1024 jul 7 15:25 #sql4b0e_10_2.myimysql> set default_tmp_storage_engine = "memory";-rw-rw---- 1 mysql mysql 8558 jul 7 15:26 #sql4b0e_10_3.frm -- memory引擎的临时表
【相关推荐:mysql视频教程】
以上就是mysql什么是临时表的详细内容。