Advanced rating system MySql database optimization

情到浓时终转凉″ 提交于 2019-12-11 10:52:24

问题


I am working on a rating system with this conditions:

There are some users and their info are stored in users table, each user has some images that are rated by the visitors (from 0 to 10), the images are stored in images table and the rates in rates table.

Now I want to get the top rated (average rate) images on a specific day, so I wrote this query:

SELECT
images.id AS iid,
images.id,
images.uid,
images.path,
images.sdate,
images.croped,
users.id,
users.provider,
users.twitterid,
users.username,
users.token,
users.secret,
users.`name`,
users.born,
users.height,
users.hair,
users.location,
users.eyes,
users.sdate,
COALESCE(x.cnt, 0) AS cnt,
COALESCE(x.arate, 0) AS arate,
x.lastdate
FROM images
LEFT OUTER JOIN (SELECT r.imageid,COUNT(r.id) as cnt,AVG(r.rate) AS arate,MAX(r.sdate) as lastdate  FROM rates r  GROUP BY r.imageid) x ON x.imageid = images.id
LEFT OUTER JOIN users on images.uid=users.id
ORDER BY
arate DESC, cnt DESC,x.lastdate DESC
LIMIT 10

but it has some problems on execute and take long time to execute! I think its main problem is here:

ORDER BY
arate DESC, cnt DESC,x.lastdate DESC

Can you find the problem of this query?

You can see the structure of my database here:

http://sqlfiddle.com/#!2/bc984/1

** Edit *

Expalin result is added:

1   PRIMARY images  ALL                 70195   Using temporary; Using filesort
1   PRIMARY <derived2>  ALL                 1743    
1   PRIMARY users   eq_ref  PRIMARY PRIMARY 4   twitter.images.uid  1   
2   DERIVED r   index       imageid 4       17776   

来源:https://stackoverflow.com/questions/12357075/advanced-rating-system-mysql-database-optimization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!