Sql至尊优化

时间:2017-09-22 13:33:44

标签: mysql join

我有一个非常尴尬的SQL查询,我无法想象如何优化它甚至更多。

SELECT dc.main_photo,d.trending, dc.reviews_num, dc.thumb_updated, dc.avg_overall_rating AS overall_rating, dc.photos_num, d.id, d.name, d.showname, d.blur_rating, d.approved, d.address, d.pref_contact_option, d.phone, d.phone2, d.website,d.flag_nofake, d.website2, d.website3, d.website4, d.tattoos, d.smokes, d.tranny, d.lat, d.lng, d.moved_to_id, d.admin_notes, d.closed, d.verified_by_admin, ci.city_name, ci.city_id, co.country_id, co.country_name, co.country_iso, IF (dc.photos_num > 0 , 1, 0) AS has_photo,eth.ethnicity_name as ethnicity, prop.prop_value as age,
r.updated_at as newest_review_date, d.bkp_last_online, d.featured 
FROM dancers d 
INNER JOIN dancers_counters dc ON d.id = dc.dancer_id
LEFT JOIN reviews r ON r.id = dc.last_review_id
INNER JOIN countries co ON co.country_id = d.country_id
LEFT JOIN cities ci ON ci.city_id = d.city_id
left join ethnicities eth on eth.ethnicity_id = d.ethnicity 
left join all_properties prop on prop.id = d.age 
WHERE  d.approved=1 AND d.moved_to_id = 0 AND d.country_id=44
ORDER BY  d.featured DESC , d.closed ASC, has_photo DESC, d.trending DESC, newest_review_date DESC 
LIMIT 19965, 15

问题是此查询需要

 Showing rows 19965 - 19979 (15 total, Query took 0.4739 seconds.) [featured: 0 - 0] [closed: 0 - 0] [trending: 0 - 0]

aproximatelly 0.5秒,考虑到可以在页面中为每个用户多次调用此查询。 试图解释查询,我有这个:http://prntscr.com/gocfb3(抱歉,我无法附加)。 无论如何,我可以进一步优化它吗?或者这是我从这个查询得到的最大值?

P.S尝试使用子选项,让所有舞者进入“where”子句,但这只会让我花费更多的时间来进行查询。

1 个答案:

答案 0 :(得分:0)

设置复合索引: d.approved,d.moved_to_id,d.country_id,d.city_id,d.ethnicity,d.age

和: 的 d.approved,d.moved_to_id,d.country_id

和: d.city_id,d.ethnicity,d.age

和: 的 dc.dancer_id,dc.last_review_id

然后尝试使用Explain重新测试查询,以查看MySQL优化器选择的索引。

ORDER BY& LIMIT语句是导致查询缓慢的原因,因为MySQL需要在返回有限行之前先对整个表进行排序和扫描。由于您要对来自多个表的列进行排序,因此MySQL优化器别无选择,只能执行文件排序而不是对任何索引进行排序。如果可能,只对来自一个表(dancer表)的列进行排序,并在这些列上添加复合索引。