所以,我有以下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