请帮助我优化有关获取电影的reccomended(rec)的查询。我有很多记录,查询运行速度很慢。以下查询运行2分钟
SELECT rec.toMovieID, sum(rec.score)
FROM rec
WHERE movieID in
(SELECT movieid as movieID FROM userFavorites as ufv WHERE ufv.userid = 29)
GROUP BY rec.toAMovieID
ORDER BY rec.score DESC
LIMIT 10
你认为我可以更优化吗?
答案 0 :(得分:2)
您可以使用内部联接而不是子选择
SELECT
rec.toMovieID,
sum(rec.score)
FROM rec INNER JOIN userFavorites ON rec.movieID = userFavorites.movieid
WHERE
userid = 29
GROUP BY rec.toAMovieID
ORDER BY rec.score DESC
LIMIT 10
您应该在where子句中的行上设置索引,至少对于movieid和userid。 (如果还没有完成)
答案 1 :(得分:1)
您可以使用exists
:
SELECT rec.toMovieID, sum(rec.score)
FROM rec r
WHERE EXISTS (SELECT 1 FROM userFavorites as ufv WHERE ufv.userid = 29 and ufv.MovieId = r.MovieId)
GROUP BY rec.toAMovieID
ORDER BY rec.score DESC
LIMIT 10;
由于重复记录,您必须小心使用join
。