关于电影主题的sql有问题

时间:2016-02-14 19:18:47

标签: mysql sql

Movie(mID int, title text, year int, director text);
Reviewer(rID int, name text);
Rating(rID int, mID int, stars int, ratingDate date);

对于每位导演,将导演的名字连同他们所导演的影片的标题一起归还所有影片中的最高评分,以及该评级的价值。忽略导演为NULL的电影。

我被困在最高评级部分。

select title, director
from Movie natural join Rating
where director is not NULL

我知道我真的不能写出来。

2 个答案:

答案 0 :(得分:0)

这是使用带有max聚合的子查询的一个选项:

select m.title, m.director, r.stars
from movie m
    join rating r on m.mid = r.mid
    join (select director, max(stars) maxstars
          from rating join movie on rating.mid = movie.mid
          group by director) maxr on m.director = maxr.director
                          and r.stars = maxr.maxstars
where m.director is not null

当我意识到您需要group by director而不是movie来获得每个导演的max(stars)时编辑。

答案 1 :(得分:0)

select distinct director, title, stars
from (movie join rating using (mid)) m
where stars in (select max(stars) 
                from rating join movie using (mid) 
                where m.director = director);