Mysql 使用临时表比较数据差异以及 临时表的优化

-- 创建内存级别带索引的临时表
CREATE TEMPORARY TABLE 'atest'(
'id' int(11) NOT NULL AUTO_INCREMENT,
'pid' bigint(20) Default 0,
'sid' bigint(20) Default 0,
KEY 'index_pid' ('pid'),
KEY 'index_sid' ('sid')
)  ENGINE =MEMORY DEFAULT CHARSET=utf8;


CREATE TEMPORARY TABLE 'btest'(
'pid' bigint(20) Default 0,
'sid' bigint(20) Default 0,
KEY 'index_pid' ('pid'),
KEY 'index_sid' ('sid')
)  ENGINE =MEMORY DEFAULT CHARSET=utf8;

insert into atest select id ,pid ,sid from tb_parent_student;
insert into btest select pid ,sid from  tb_child join tb_parent on pid=pid;

-- 使用普通方式创建默认临时表方法 create temporary table atest(
select id ,pid ,sid from tb_parent_student); create temporary table btest(select pid ,sid from tb_child join tb_parent on pid=pid); select *From atest; select *From btest; -- Exists 比较两个结果集的差异信息 select *From atest where not Exists (select *From btest where atest.pid=btest.pid and atest.sid=btest.sid); select *From btest where not Exists (select *from atest where atest.pid=btest.pid and atest.sid=btest.sid); -- left join select *From atest m left join btest as a on m.pid=a.pid and m.sid=a.sid; select *From btest m left join atest as a on m.pid=a.pid and m.sid=a.sid;

-- 用完及时释放
drop TEMPORARY TABLE atest;
drop TEMPORARY TABLE btest;

 其中:atest 和btest 两个临时表格的数据都有近二十万数据。

使用普通方式创建默认临时表执行比较结果集语句耗时(其实还没执行完我受不了了直接断开了,后来实际测试大致执行了38分钟!):

使用内存级别加索引方式创建临时表执行比较结果耗时:

知道优化后查询会快很多,但是没想到能快这么多。

 tips: 临时表默认大小限制好像是 16M 如果报  XXXtable is full的话可以修改临时表大小配置进行修改。

如果是Linux下就修改Mysql的配置文件/etc/my.cnf,在[mysqld]下添加/修改两行:
tmp_table_size = 256M
max_heap_table_size = 256M

如果是win下就修改Mysql的配置文件my.ini,在[my.ini]下添加/修改两行:
tmp_table_size = 256M
max_heap_table_size = 256M
原文地址:https://www.cnblogs.com/chongyao/p/12859190.html