>优质博文:IT-BLOG-CN

(图片来源网络,侵删)
一、慢查询优化基本步骤
【1】先运行看看是否真的很慢,注意设置SQL_NO_CACHE(查询时不使用缓存);
【2】where条件单表查,锁定最小返回记录表。这句话的意思是把查询语句的 where都应用到表中返回的记录数最小的表开始查起,单表每个字段分别查询,看哪个字段的区分度最高;

(图片来源网络,侵删)
【3】explain查看执行计划,是否与2预期一致(从锁定记录较少的表开始查询);
【4】order by limit 形式的 sql语句让排序的表优先查;
【5】了解业务方使用场景;
【6】加索引时参照建索引的几大原则;
二、几个慢查询案例
1、复杂语句写法
很多情况下,我们写 SQL只是为了实现功能,这只是第一步,不同的语句书写方式对于效率往往有本质的差别,这要求我们对 mysql的执行计划和索引原则有非常清楚的认识,请看下面的语句:
select distinct cert.emp_id from cm_log cl inner join ( select emp.id as emp_id, emp_cert.id as cert_id from employee emp left join emp_certificate emp_cert on emp.id = emp_cert.emp_id where emp.is_deleted=0 ) cert on ( cl.ref_table='Employee' and cl.ref_oid= cert.emp_id ) or ( cl.ref_table='EmpCertificate' and cl.ref_oid= cert.cert_id ) where cl.last_upd_date >='2013-11-07 15:03:00' and cl.last_upd_date='2013-11-07 15:03:00' and cl.last_upd_date='2013-11-07 15:03:00' and cl.last_upd_date= 2875 and oei.node_right = 2875 and oei.node_right = 2875 and oei.node_right = 2875 and oei.node_right