电影数据库上的PHP mySQL查询速度极慢

时间:2013-04-27 07:14:25

标签: php mysql sql

我有一个php文件查询mySql数据库,在一个表上设置电影,在另一个表上设置movieRatings。我想算一下特定电影的“5星”,“4星”等评分。我的查询有效,但是它非常慢,因为我意识到它会通过整个movieRatings表对我要查找的每部电影进行5次。

我的查询:

$sql = "SELECT * 
                FROM MOVIE_INFO,
                (SELECT count(ratingValue) as star5 FROM MOVIE_RATINGS2 WHERE itemID=$b[0] AND ratingValue = 5 ) SUB,
                (SELECT count(ratingValue) as star4 FROM MOVIE_RATINGS2 WHERE itemID=$b[0] AND ratingValue = 4 ) SUB1,
                (SELECT count(ratingValue) as star3 FROM MOVIE_RATINGS2 WHERE itemID=$b[0] AND ratingValue = 3 ) SUB2,
                (SELECT count(ratingValue) as star2 FROM MOVIE_RATINGS2 WHERE itemID=$b[0] AND ratingValue = 2 ) SUB3,
                (SELECT count(ratingValue) as star1 FROM MOVIE_RATINGS2 WHERE itemID=$b[0] AND ratingValue = 1 ) SUB4

                WHERE movieID = $b[0]";

我想如果我可以从该特定电影的电影评级中拉出一次子集,它会极大地加速它,但我不记得该怎么做。

1 个答案:

答案 0 :(得分:3)

您正在执行多个子选择。相反,尝试分组查询,例如

SELECT ratingValue, COUNT(ratingValue) FROM MOVIE_INFO
WHERE movieID = $b[0]
GROUP BY ratingValue

每个星级类别您将获得一行。第一列将是评级本身(例如1),第二列将是具有该星数的评级数。