Advanced rating system MySql database optimization

2019-08-01 03:43发布

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   

0条回答
登录 后发表回答