2017-09-22 23 views
-1

我有一個非常尷尬的SQL查詢,我不知道如何優化它甚至比它更多。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] 

aproximatelly0.5秒這是很多考慮到這個查詢可以被稱爲在頁面了很多次,爲每一個用戶。 試圖解釋查詢,我有這個:http://prntscr.com/gocfb3(對不起,我不能附上)。 無論如何,我可以優化它甚至更多?或者這是我可以從這個查詢得到的最大值?

P.S試用一個子選擇,讓所有進入「where」子句的舞者進入,但這隻會讓我花更多的時間用於查詢。

+0

你不能廣告緩存層? –

+0

現在我正在爲緩存系統使用memcache,並且我緩存每個查詢,我遇到的問題是查詢未緩存,並且第二個有更多用戶嘗試訪問該站點,然後此查詢需要一個冗長looong時間。我使用的邏輯,每當我嘗試查詢某些東西時,我首先驗證它是否在memcache中,如果它在那裏,我從那裏檢索它,如果沒有,我查詢並將它放入memcache 1h。 –

回答

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.d ancer_id,dc.last_review_id

然後嘗試使用Explain重新測試查詢以查看MySQL優化器選擇哪個索引。

ORDER BY & LIMIT語句是導致查詢速度慢的原因,因爲MySQL在返回有限的行之前需要對整個表進行排序和掃描。由於您對來自多個表的列進行排序,因此MySQL優化器別無選擇,只能執行文件排序而不排序任何索引。如果可能的話,只對來自一個表的列進行排序(dancer表),並在這些列上添加一個複合索引。

+0

嗨,現在,添加了這些索引,查詢是0.5023秒,做了一次測試,並從排序中刪除了不是來自d的2列。表格,它的時間戳從0.5到0.2990。 –