我需要有关mysql查询的帮助,在主表上加入了2个计数表。它涉及用户活动 - 计算和总结他们的活动(评论和文章)到一个变量,然后由DESC订购。主表是用户,secundary是文章和评论。
SELECT u.id, u.username, u.avatar,
IF(comm.id, COUNT(DISTINCT comm.id), 0) AS count_comments,
IF(comm.votes, SUM(DISTINCT comm.votes), 0) AS count_comments_votes,
IF(article.id, COUNT(article.id), 0) AS count_articles,
IF(article.views, SUM(DISTINCT article.views), 0) AS count_articles_views,
(IF(comm.id AND comm.votes>2, COUNT(comm.id)*50, 0) + IF(comm.votes, SUM(comm.votes)*10, 0) + IF(article.id, COUNT(article.id)*200, 0) + IF(article.views, SUM(article.views)*1, 0)) AS points
FROM users AS u
LEFT JOIN comments AS comm ON comm.id_user=u.id AND comm.date>='2013-05-01' AND comm.date<='2013-06-24'
LEFT JOIN articles AS article ON article.id_user=u.id AND article.date>='2013-05-01' AND article.date<='2013-06-24'
WHERE u.is_active='1'
GROUP BY u.id
HAVING points>0
ORDER BY points DESC
查询完成了 11-13
秒,这太长了。有任何想法吗 ?也许索引一些字段可以加快查询速度?