sqlzoo-More JOIN operations学习笔记

movie表

id title yr director budget gross
10003 “Crocodile” Dundee II 1988 38 15800000 239606210
10004 'Til There Was You 1997 49 10000000

actor表

id name
20 Paul Hogan
50 Jeanne Tripplehorn

casting表

movieid actorid ord
10003 20 4
10004 50 1

6.Obtain the cast list for ‘Casablanca’. (The cast list is the names of the actors who were in the movie.)

SELECT name FROM actor JOIN casting ON id=actorid WHERE movieid=11768

7.Obtain the cast list for the film ‘Alien’
第一种方法:

SELECT name FROM actor JOIN casting ON id=actorid 
    WHERE casting.movieid=(SELECT id FROM movie WHERE title='Alien')

第二种方法:

SELECT name FROM actor JOIN casting ON id = actorid
    JOIN movie ON movie.id = casting.movieid WHERE title = 'Alien'

8.List the films in which ‘Harrison Ford’ has appeared

SELECT title FROM movie JOIN casting ON id=movieid 
    WHERE actorid=(SELECT id FROM actor WHERE name='Harrison Ford')

10.List the films together with the leading star for all 1962 films.
第一种方法:

SELECT title,name FROM movie JOIN casting ON id=movieid 
    JOIN actor ON actor.id=casting.actorid WHERE yr=1962 AND ord=1

第二种方法:

SELECT title,name FROM movie JOIN actor ON yr=1962
    JOIN casting ON movie.id = casting.movieid AND actor.id = casting.actorid AND ord =1

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 yr,COUNT(title) FROM
  movie JOIN casting ON movie.id=movieid
         JOIN actor   ON actorid=actor.id
where name='John Travolta'
GROUP BY yr
HAVING COUNT(title)=(SELECT MAX(c) FROM
(SELECT yr,COUNT(title) AS c FROM
   movie JOIN casting ON movie.id=movieid
         JOIN actor   ON actorid=actor.id
 where name='John Travolta'
 GROUP BY yr) AS t
)

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

SELECT title,name FROM movie 
    JOIN casting ON movie.id=casting.movieid 
    JOIN actor ONa ctor.id=casting.actorid 
    WHERE movie.id in 
    (select movieid from actor join casting on actorid=id and name='Julie Andrews') 
    and casting.ord=1

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 = casting.actorid 
    JOIN movie ON movie.id = casting.movieid 
    WHERE ord = 1
    GROUP BY name
    HAVING COUNT(title)>=30
    ORDER BY name

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

SELECT title,COUNT(actorid) FROM movie 
    JOIN casting ON movie.id=casting.movieid 
    WHERE yr=1978 GROUP BY title ORDER BY COUNT(actorid) DESC,title

15.List all the people who have worked with ‘Art Garfunkel’.

SELECT name FROM actor 
    JOIN casting ON id=actorid WHERE movieid IN (SELECT movieid FROM casting 
    JOIN actor ON id=actorid WHERE name='Art Garfunkel') AND name!='Art Garfunkel'

你可能感兴趣的:(MySQL)