原SQL:
SELECT a.*,b.*,b.diff_num,b.supplier_id,b.num,b.price,c.product_id,c.old_spec_sku,c.new_purchase_price,d.old_parent_sku,d.product_cname FROM hexin_erp_storage_out_main a left JOIN hexin_erp_storage_out_detail b on a.id=b.main_id left JOIN hexin_erp_product_spec c on b.spec_id=c.id left JOIN hexin_erp_product d on d.id=c.product_id
WHERE a.status = 2 AND ( a.create_time >= 1564588800 AND a.create_time <= 1567267199 ) ORDER BY a.id desc LIMIT 161000,1000;
优化后SQL:
SELECT a.*,b.*,b.diff_num,b.supplier_id,b.num,b.price,c.product_id,c.old_spec_sku,c.new_purchase_price,d.old_parent_sku,d.product_cname FROM
(select aa.id from hexin_erp_storage_out_main aa where aa.create_time >= 1564588800 AND aa.create_time <= 1567267199 ORDER BY aa.id desc LIMIT 161000,1000 ) aaa
inner join hexin_erp_storage_out_main a on aaa.id=a.id and a.status = 2
left JOIN hexin_erp_storage_out_detail b on a.id=b.main_id
left JOIN hexin_erp_product_spec c on b.spec_id=c.id
left JOIN hexin_erp_product d on d.id=c.product_id
前台执行对比:
修改前:
修改后:
执行时间差了10倍
核心要点:
我们可以先将数据量最大表的满足条件的ID查询出来,创建临时表,再用这个临时表去关联这个表本身以及其他表。