0

我需要 mysql 查询方面的帮助,在主表上加入了 2 个计数表。它与用户活动有关 - 将他们的活动(评论和文章)计数和汇总到一个变量中,然后按 DESC 对其进行排序。主表是用户,次表是文章评论

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-13sec 才能完成,这太长了。有任何想法吗 ?也许索引某些字段可以加快查询速度?

4

0 回答 0