2012-04-11 65 views
3

我正在解决www.db-class.com练习。即使时间晚了,问题仍然很有趣。我偶然发现了最后一项任务,无法找出解决方案。来自www.db-class.com的SQL查询

的SQL方案如下:

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

整个数据库可以obtainted here

的问题如下:

Q12对于各家所长,回报导演的名字连同他们指导的电影名称( )在其所有电影中获得最高评级 ,而val该等级的评级。 忽略导演为NULL的电影。

给予更多的具体细节有什么问题就在这里:

一个查询

select m.mid, m.title, max(r.stars) as stars 
from rating r natural join movie m 
where m.director is NOT NULL group by m.mid 

最受好评的电影收益的ID:

101 Gone with the Wind  4 
103 The Sound of Music  3 
104 E.T.      3 
107 Avatar     5 
108 Raiders of the Lost Ark 4 

另一个查询

select m.director, max(r.stars) as stars 
from rating r natural join movie m 
where m.director is NOT NULL group by m.director 
与大多数额定电影的导演为他们个

回报名称:

James Cameron  5 
Robert Wise   3 
Steven Spielberg 4 
Victor Fleming  4 

如何加入查询和获取最受好评的影片为导演的名字和星星:

James Cameron  Avatar     5 
Robert Wise  The Sound of Music  3 
Steven Spielberg Raiders of the Lost Ark 4 
Victor Fleming  Gone with the Wind  4 

回答

2

在我看来,这只是一个gretest-n-per-group问题。甚至还有一个tag :)

与典型情况唯一的区别是分组数据(director)在一个表中,并且用于比较的数据在另一个表(星号)中。所以,如果你看到标签这样的问题,你应该找到类似的例子。

我建议你先解决它,先假设你的所有数据都在一张表中(可怕,但更容易解决......至少对我而言)。然后切换到拆分的数据。

剧透:

我认为这是如何解决这个所以就来看看它只有在你已经提出了一个解决方案。

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 
+0

解决方案返回NULL导向器并且不会获取标题。这个任务很简单,没有标题或没有导演,但是当他们都需要时,它更加棘手 – 2012-04-11 06:39:10

+0

不是真的:)我添加了电影标题并删除了空导演(我不确定是否忽略导演为空的电影意味着将它们从结果中删除,以防万一,我做到了) – 2012-04-11 06:43:29

+0

我找到了一个类似的解决方案,但它为所有电影提供了多个导演。答案显然需要每部电影最多一名导演(星级) – 2012-04-11 06:46:34

0

建议:

  1. 创建一个简单的查询,列出了所有董事(容易)

  2. 做一个“加入”链接每部电影 - 用其所长一起 - 到相应的等级

  3. 采取步骤2中的“加入”和“组”的导演,做一个“最大(额定)”

+0

我做到了。它为所有电影提供多个导演。答案显然需要每部电影最多一个导演(星星)。 – 2012-04-11 06:45:14