所以,我有以下SQL優化MySQL查詢
SELECT i.id, r.full_name, i.file_name, i.lat, i.lon, c.name as
category_name,
NOW() - i.timestamp AS age,
(SELECT count(*) FROM votes WHERE image_id = i.id) as total_votes
FROM images i INNER JOIN registrations r
ON i.user_id = r.id
INNER JOIN categories c ON i.category_id = c.id
WHERE i.moderated=1
ORDER BY total_votes DESC
LIMIT 25
這在平均10-15秒對我的本地環境中運行。
刪除ORDER BY部分將其降爲0.02ish。
有什麼方法可以加快主要語句中的排序?
更新2: 重寫了查詢,並增加了一些指標在
查詢
SELECT votes.image_id, count(votes.id) as total_votes,
images.file_name, images.lat, images.lon, NOW() - images.timestamp AS age,
registrations.full_name,
categories.name
FROM votes
LEFT JOIN images
ON votes.image_id = images.id
LEFT JOIN registrations
ON images.user_id= registrations.id
LEFT JOIN categories
ON images.category_id = categories.id
GROUP BY votes.image_id
ORDER BY total_votes DESC
LIMIT 25
當前解釋查詢:
首先發布EXPLAIN的輸出以供查詢 – Prix 2014-09-04 08:42:04
您是否對所有加入的列都有索引? – DanFromGermany 2014-09-04 08:42:05
@Prix - 更新與解釋 – 2014-09-04 08:53:42