如何查询检索评分最高的电影?

时间:2013-07-05 09:57:01

标签: mysql greatest-n-per-group

我有以下表格:

Movie ( mID, title, year, director ) 

Reviewer ( rID, name ) 

Rating ( rID, mID, stars, ratingDate ) 

我想要做的是获取导演的名字以及他所指导的电影名称并获得最高评价。

例如,如果史蒂芬斯皮尔伯格指导了两部电影(即AB)分别获得3星和5星评级,那么查询必须显示斯蒂芬斯皮尔伯格和B(电影与最高评级)。

PS:我只需要帮助。希望我清楚自己。请询问是否需要更多信息或解释。

5 个答案:

答案 0 :(得分:0)

设置子选择以获得导演和最高评级: -

SELECT director, MAX(stars)
FROM Movie
INNER JOIN Rating
ON Movie.mID = Rating.mID
INNER JOIN
(
    SELECT director, MAX(stars) AS MaxRating
    FROM Movie
    INNER JOIN Rating
    ON Movie.mID = Rating.mID
    GROUP BY director
) Sub1
ON Movie.directort = Sub1.director
AND Rating.stars = Sub1.MaxRating

但我认为你需要更多细节。你现在似乎没有使用评论者表,我认为一部电影可能有几个不同的评论者可以给出不同的评分。如果是这样,您可能希望使用上面的子选择来加入评级表(标题和星标上的macthign),以及从评论表到评论者表。

答案 1 :(得分:0)

为什么不尝试这个,

SELECT TITLE,DIRECTOR FROM MOVIE,
(SELECT MAX(STARS),mID FROM RATING GROUP BY mID) R
WHERE MOVIE.mID=R.mID

答案 2 :(得分:0)

你去吧

SELECT q.* FROM (SELECT m.*,MAX(r.`stars`) AS maxrating FROM `movie` m 
INNER JOIN `rating` r ON (m.`mID` = r.`mID` ) 
GROUP BY r.`mID` ORDER BY maxrating DESC ) q GROUP BY q.director 
ORDER BY q.maxrating DESC 

我相信这个问题来自quiz of DB class provided by stanford university

Here is your fiddle

答案 3 :(得分:0)

另一种方法是:

select m.title, max(r.stars) as stars
from rating r
inner join movie m on r.mid = m.mid
group by r.mid
order by m.title

答案 4 :(得分:-1)

此代码应该足够了:

select distinct m1.director, m1.title, r1.stars from movie m1
join rating r1 on m1.mID = r1.mID
left join (
    select m2.director, r2.stars from movie m2
    join rating r2 on m2.mID = r2.mID
) s on m1.director = s.director and r1.stars < s.stars
where s.stars is null and m1.director is not null;