我正在研究具有以下条件的评级系统:
有些用户及其信息存储在用户表中,每个用户都有一些由访问者评分的图像(从0到10),图像存储在图像中表和费率表中的费率。
现在我想获得特定日期的最高评分(平均费率)图片,所以我写了这个查询:
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
但它在执行时有一些问题,需要很长时间才能执行!我认为它的主要问题在于:
ORDER BY
arate DESC, cnt DESC,x.lastdate DESC
您能找到此查询的问题吗?
您可以在此处查看我的数据库结构:
http://sqlfiddle.com/#!2/bc984/1
** 修改 *
添加了Expalin结果:
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