1. 程式人生 > >SQLZOO錯題總結

SQLZOO錯題總結

1.More Join (http://zh.sqlzoo.net/wiki/More_JOIN_operations)

第10題 List the films together with the leading star for all 1962 films.

select movie.title, actor.name
from movie join casting on (movie.id = casting.movieid)
join actor on (actor.id = casting.actorid)
where movie.yr = 1962 and casting.ord = 1

 

2.11題

Which were the busiest years for 'John Travolta', show the year and the number of movies he made each year for any year in which he made more than 2 movies.

select movie.yr, count(movie.id)
from movie join casting on (movie.id = casting.movieid) join actor on (actor.id = casting.actorid) where actor.name = 'John Travolta' 
group by movie.yr
having count(movie.id) >= all (select count(movie.id) from movie join casting on (movie.id = casting.movieid) join actor on (actor.id = casting.actorid) where actor.name = 'John Travolta' 
group by movie.yr)
之所以要
group by movie.yr

是因為題目要求以each year為單位進行資料搜尋,因此要返回的movie.id的個數應該是在各個yr底下的。

至於having條件句的限定,是因為題目要求選出 the busiest year,故一個count(movie.id)>all(【把前面的語句全部重複了一遍】)。此處沒有寫入每年電影數>2這個限制要求,是因為已經有了比全部年份的數量大這個限制了,就不用再寫。

12.

List the film title and the leading actor for all of the films 'Julie Andrews' played in.

我的錯誤答案:
select title,name
from movie join actor on movie.id=actor.id join casting on movieid=movie.id
where movie.id=(select movieid from casting join actor on actorid=actor.id where name='Julie Andrews' and ord=1)

正確答案:

select movie.title, actor.name
from movie join casting on (movie.id = casting.movieid)
join actor on (actor.id = casting.actorid)
where casting.ord = 1
and
movie.id in (select movie.id from movie
join casting on (movie.id = casting.movieid)
join actor on (actor.id = casting.actorid)
where actor.name = 'Julie Andrews')

13.Obtain a list, in alphabetical order, of actors who've had at least 30 starring roles.

select name
from actor join casting on actor.id=actorid
where ord=1
group by name,actorid
having count(actorid)>=30
order by actor.name

14.List the films released in the year 1978 ordered by the number of actors in the cast, then by title.

select movie.title, count(actorid) 
from movie join casting on (movie.id = casting.movieid) join actor on (actor.id = casting.actorid)
where movie.yr = 1978 
group by movie.title
order by 2 desc,title;