简体   繁体   English

电影数据库上的PHP MySQL极慢查询

[英]Extremely slow PHP mySQL query on movies database

I have a php file querying a mySql database set up with movies on one table and movieRatings on another. 我有一个php文件,用于查询mySql数据库,该数据库在一个表上设置了电影,在另一个表上设置了movieRatings。 I want to count the number of "5 star", "4 star", etc ratings that a particular movie has. 我想计算特定电影具有的“ 5星”,“ 4星”等评分。 My query works, however it is very slow as I realize it goes through the entire movieRatings table 5 times for each movie I want to look up. 我的查询有效,但是它非常慢,因为我意识到要查找的每个电影都要遍历整个movieRatings表5次。

My query: 我的查询:

$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]";

I figure if I can pull the subset from the movie ratings for that particular movie once, it would speed it up immensely, but I can't remember how to do that. 我认为,如果可以一次从特定电影的电影分级中提取子集,它将极大地加快它的速度,但是我不记得该怎么做。

You are performing multiple sub-selects. 您正在执行多个子选择。 Instead, try a grouping query, eg 相反,请尝试进行分组查询,例如

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

You will get back one row per star category. 每个星级类别将返回一行。 The first column will be the rating itself (eg 1) and the second column will be the number of ratings with that number of stars. 第一列将是等级本身(例如1),第二列将是具有该星数的等级数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM