把not in 改成not exists后的优化

 
把not in 改成not exists后的优化

近期,OA数据库里面存在一条慢sql,其执行时间为3分16秒。这条慢sql语句每个月可能会运行几次,但其运行后,总会导致数据库cpu利用率飙升。然后我就对这个慢sql语句进行了改写测试,改写后的运行时间降为13s(虽然还是很慢,但已经速度提升了18倍)。




具体分析过程如下:
通过慢日志捕捉到的慢sql及其运行时间:
1 select id,start_member_id,start_date,modify_member_id,modify_date from formmain_0141 where id not in (select content_data_id from ctp_content_all where content_template_id='6890363387462501722' and content_data_id is not null  ) limit 20000, 10000\G
Empty set (3 min 2.01 sec)

可见,生产中,该语句运行时间是3分2秒。

我们来看看其执行计划,为什么这么慢:

把not in 改成not exists后的优化
把not in 改成not exists后的优化



2、我改写后的索引,用的是 not exists ,内外交互式子查询

mysql> select id,start_member_id,start_date,modify_member_id,modify_date from formmain_0141 where not exists (select 1 from ctp_content_all where content_data_id= formmain_0141.id and content_data_id is not null and content_template_id='6890363387462501722') limit 20000, 10000 ;
Empty set (13.84 sec)

看到用not exists后,执行时间降到13秒,效率有显著提升。

我们再看一下优化后语句的执行计划:

把not in 改成not exists后的优化



把not in 改成not exists后的优化

把not in改写为not exists快的原因,我想用MysqL 5.6的新特性ICP的原理来解释,在改写后的sql语句中,MysqL在从 ctp_content_all表中取出数据的同时,就开始判断是否可以在formmain_0141表中进行id过滤,从而大大减少了上层对sql层的记录索引,提高数据库整体性能
反观优化前的那条sql语句,它是把 ctp_content_all 表里面所有符合条件的记录都取出来后,再到 formmain_0141表里进行id字段过滤,所以慢。

相关文章

这篇文章主要介绍“hive和mysql的区别是什么”,在日常操作中...
这篇“MySQL数据库如何改名”文章的知识点大部分人都不太理解...
这篇文章主要介绍“mysql版本查询命令是什么”的相关知识,小...
本篇内容介绍了“mysql怎么修改字段的内容”的有关知识,在实...
这篇文章主要讲解了“mysql怎么删除unique约束”,文中的讲解...
今天小编给大家分享一下mysql怎么查询不为空的字段的相关知识...