mysql查询优化

问题:

使用limit a, offset b 查询时 当b的值过大时, 会出现性能问题

过程是用offset查询会查询a+b行数据,再将b行数据废弃。

优化前sql

执行耗时 2分钟
select wk_material_audit.*, wk_dsp.name as dspName
from wk_material_audit
left join wk_dsp on wk_dsp.id = wk_material_audit.dsp_id
where dsp_id = 'Xunfei' and status = 0
order by wk_material_audit.updated_at desc limit 50 offset 300000;

优化后sql

执行耗时 0.64秒
--- 查询优化后: 耗时0.11秒
select t.*, d.name as dspName from (
select id from wk_material_audit where dsp_id = 'XunFei' and status = 0
order by wk_material_audit.updated_at desc limit 50 offset 400000
) as q
join wk_material_audit as t on t.id = q.id
left join wk_dsp as d on d.id = t.dsp_id

参考

  1. http://stackoverflow.com/questions/4481388/why-does-mysql-higher-limit-offset-slow-the-query-down
  2. http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/

你可能感兴趣的:(mysql查询优化)