SQLZOO学习笔记

文章目录

  • Select basics
    • QUIZ AND NOTES
  • select from world Tutial
    • The world table.
  • Select from nobel
  • select within select
    • Alias
    • Multiple Results
    • Subquery on the SELECT line
    • Operators over a set
    • Tests
  • Sum and count
    • Aggregates
    • Distinct
    • Order by
    • World Country Profile: Aggregate functions
  • The JOIN operation
    • JOIN and UEFA EURO 2012
  • More JOIN operations
    • Movie Database
      • movie
      • actor
      • casting

Select basics

world
name continent area population gdp
Afghanistan Asia 652230 25500100 20343000000
Albania Europe 28748 2831741 12960000000
Algeria Africa 2381741 37100000 188681000000
Andorra Europe 468 78115 3712000000
Angola Africa 1246700 20609294 100990000000

Introducing the world table of countries

  1. The example uses a WHERE clause to show the population of ‘France’. Note that strings (pieces of text that are data) should be in ‘single quotes’; Modify it to show the population of Germany
    SELECT population
    FROM world
    WHERE name = ‘Germany’
    Scandinavia
  2. Show the name and the population for ‘Sweden’, ‘Norway’ and ‘Denmark’.
    SELECT name, population
    FROM world
    WHERE name IN (‘Sweden’, ‘Norway’, ‘Denmark’);
    Just the right size
  3. Which countries are not too small and not too big?BETWEEN allows range checking (range specified is inclusive of boundary values). The example below shows countries with an area of 250,000-300,000 sq. km. Modify it to show the country and the area for countries with an area between 200,000 and 250,000.
    SELECT name, area
    FROM world
    WHERE area BETWEEN 200000 AND 250000

QUIZ AND NOTES

Some questions concerning basic SQL statements
name region area population gdp
Afghanistan South Asia 652225 26000000
Albania Europe 28728 3200000 6656000000
Algeria Middle East 2400000 32900000 75012000000
Andorra Europe 468 64000

  1. Select the code which produces this table
    name population
    Bahrain 1234571
    Swaziland 1220000
    Timor-Leste 1066409
    SELECT name, population FROM world WHERE population BETWEEN 1000000 AND 1250000
    BETWEEN allows range checking (range specified is inclusive of boundary values).

  2. Pick the result you would obtain from this code:
    SELECT name, population
    FROM world
    WHERE name LIKE “Al%”
    Albania 3200000
    Algeria 32900000
    Table-E

  3. Select the code which shows the countries that end in A or L
    SELECT name FROM world WHERE name LIKE ‘%a’ OR name LIKE ‘%l’
    “%”occupies the space of the items that we do not show in the checking quotations.

  4. Pick the result from the query
    SELECT name,length(name)
    FROM world
    WHERE length(name)=5 and region=‘Europe’
    name length(name)
    Italy 5
    Malta 5
    Spain 5

  5. Pick the result you would obtain from this code:
    SELECT name, area*2 FROM world WHERE population = 64000
    Andorra 936

  6. Select the code that would show the countries with an area larger than 50000 and a population smaller than 10000000
    SELECT name, area, population FROM world WHERE area > 50000 AND population < 10000000

  7. Select the code that shows the population density of China, Australia, Nigeria and France
    SELECT name, population/area FROM world WHERE name IN (‘China’, ‘Nigeria’, ‘France’, ‘Australia’)
    Checking a list The word IN allows us to check if an item is in a list.

select from world Tutial

The world table.

Some points to note:
• There is a table called world with nearly 200 records.
• The first record is Afghanistan in Asia
• The final record is Zimbabwe in Africa.
• The table has eight columns or attributes . These are:
Field Type Null Key Default Notes
name varchar(50) The English name of the country - this is the primary key.
continent varchar(60) Not strictloy continent - but these include all your favourite continents (Europe, Asia etc) plus a few others.
area decimal(10,0) YES null
population decimal(11,0) YES null
gdp decimal(14,0) YES null
capital varchar(60) YES null
tld varchar(5) YES null
flag varchar(255) YES null
An extract from the table world
name region area population gdp
Yemen Middle East 536869 21500000 12255000000
Zambia Africa 752614 11000000 4950000000
Zimbabwe Africa 390759 12900000 6192000000
Footnotes
Per Capita GDP
The per capita GDP is the GDP divided by the population. It is a rough measure of the average salary. A rich country is one with a high per capita GDP.
Original source
This data has been collected from http://www.wikidata.org - it may be a little out of date. The latest version can be found at Some changes have been made to the data - the reader should assume that errors and omissions are due to me and not the most excellent wikidata site.
Area
The area is measured in square kilometers.
GDP

Scientific Notation
Some implementations of SQL may show large numbers in scientific notation. The number 6.23 E9 means 6.23 x 10 9 which is 6.23 x 1,000,000,000 which is 6,230,000,000
A Million is 10 6 which is 1,000,000
A Billion is 10 9 which is one thousand million which is 1,000,000,000
A Trillion is 10 12 , which is one million million which is 1,000,000,000,000.

  1. Read the notes about this table. Observe the result of running this SQL command to show the name, continent and population of all countries.
    SELECT name, continent, population
    FROM world
  2. How to use WHERE to filter records. Show the name for the countries that have a population of at least 200 million. 200 million is 200000000, there are eight zeros.
    SELECT name
    FROM world
    WHERE population >= 200000000
  3. Give the name and the per capita GDP for those countries with a population of at least 200 million.
    SELECT name, gdp/population
    FROM world
    WHERE population > 200000000
  4. Show the name and population in millions for the countries of the continent ‘South America’. Divide the population by 1000000 to get population in millions.
    SELECT name, population/1000000
    FROM world
    WHERE continent = ‘South America’
  5. Show the name and population for France, Germany, Italy.
    SELECT name, population
    FROM world
    WHERE name IN (‘France’, ‘Germany’, ‘Italy’)
  6. Show the countries which have a name that includes the word ‘United’.
    SELECT name
    FROM world
    WHERE name LIKE ‘%United%’
  7. Two ways to be big: A country is big if it has an area of more than 3 million sq km or it has a population of more than 250 million. Show the countries that are big by area or big by population. Show name, population and area.
    SELECT name, population, area
    FROM world
    WHERE area > 3000000 OR population > 250000000
  8. Exclusive OR (XOR). Show the countries that are big by area or big by population but not both. Show name, population and area.
    SELECT name, population, area
    FROM world
    WHERE area > 3000000 XOR population > 250000000
  9. Show the name and population in millions and the GDP in billions for the countries of the continent’South America’. Use the ROUND function to show the values to two decimal places.
    SELECT name, ROUND(population/1000000, 2), ROUND(gdp/1000000000, 2)
    FROM world
    WHERE continent = ‘South America’
  10. Show the name and per-capita GDP for those countries with a GDP of at least one trillion (1000000000000; that is 12 zeros). Round this value to the nearest 1000. Show per-capita GDP for the trillion dollar countries to the nearest $1000.
    SELECT name, ROUND(gdp/population/1000, 0) * 1000
    FROM world
    WHERE gdp >= 1000000000000
  11. Greece has capital Athens. Each of the strings ‘Greece’, and ‘Athens’ has 6 characters. Show the name and capital where the name and the capital have the same number of characters.
    SELECT name, capital
    FROM world
    WHERE LENGTH(capital) = LENGTH(name)
  12. The capital of Sweden is Stockholm. Both words start with the letter ‘S’. Show the name and the capital where the first letters of each match. Don’t include countries where the name and the capital are the same word.
    SELECT name, capital
    FROM world
    WHERE LEFT(capital, 1) = LEFT(name, 1)
    AND capital <> name
  13. Equatorial Guinea and Dominican Republic have all of the vowels (a e i o u) in the name. They don’t count because they have more than one word in the name. Find the country that has all the vowels and no spaces in its name.
    SELECT name
    FROM world
    WHERE name LIKE ‘%a%’
    AND name LIKE ‘%e%’
    AND name LIKE ‘%i%’
    AND name LIKE ‘%o%’
    AND name LIKE ‘%u%’
    AND name NOT LIKE ‘% %’

Select from nobel

nobel
yr subject winner
1960 Chemistry Willard F. Libby
1960 Literature Saint-John Perse
1960 Medicine Sir Frank Macfarlane Burnet
1960 Medicine Peter Madawar

  1. Change the query shown so that it displays Nobel prizes for 1950.

SELECT yr, subject, winner
FROM nobel
WHERE yr = 1950

  1. Show who won the 1962 prize for Literature.

SELECT winner
FROM nobel
WHERE yr = 1962
AND subject = ‘Literature’

  1. Show the year and subject that won ‘Albert Einstein’ his prize.

SELECT yr, subject
FROM nobel
WHERE winner = ‘Albert Einstein’

  1. Give the name of the ‘Peace’ winners since the year 2000, including 2000.

SELECT winner
FROM nobel
WHERE yr >= 2000 AND subject = ‘Peace’

  1. Show all details (yr, subject, winner) of the Literature prize winners for 1980 to 1989 inclusive.

SELECT *
FROM nobel
WHERE subject = ‘Literature’
AND (yr >= 1980 AND yr <= 1989)

  1. Show all details of the presidential winners:

    Theodore Roosevelt
    Woodrow Wilson
    Jimmy Carter
    Barack Obama
    SELECT *
    FROM nobel
    WHERE winner IN (‘Theodore Roosevelt’, ‘Woodrow Wilson’, ‘Jimmy Carter’, ‘Barack Obama’)

  2. Show the winners with first name John.

SELECT winner
FROM nobel
WHERE winner LIKE ‘John%’

  1. Show the year, subject, and name of Physics winners for 1980 together with the Chemistry winners for 1984.

SELECT *
FROM nobel
WHERE (yr = 1980 AND subject = ‘Physics’)
OR (yr = 1984 AND subject = ‘Chemistry’)

  1. Show the year, subject, and name of winners for 1980 excluding Chemistry and Medicine.

SELECT *
FROM nobel
WHERE yr = 1980
AND subject NOT IN (‘Chemistry’, ‘Medicine’)

  1. Show year, subject, and name of people who won a ‘Medicine’ prize in an early year (before 1910, not including 1910) together with winners of a ‘Literature’ prize in a later year (after 2004, including 2004).

SELECT *
FROM nobel
WHERE (yr < 1910 AND subject = ‘Medicine’)
OR (yr >= 2004 AND subject = ‘Literature’)

  1. Find all details of the prize won by PETER GRÜNBERG.

SELECT *
FROM nobel
WHERE winner = ‘PETER GRÜNBERG’
/*
Ü这个符号怎么打?按住ALT键,通过数字小键盘依次按‘0220’即可。
*/

  1. Find all details of the prize won by EUGENE O’NEILL

SELECT *
FROM nobel
WHERE winner = ‘EUGENE O’NEILL’

  1. Knights in order. List the winners, year and subject where the winner starts with Sir. Show the the most recent first, then by name order.

SELECT winner, yr, subject
FROM nobel
WHERE winner LIKE ‘Sir%’
ORDER BY yr DESC, winner

  1. Show the 1984 winners and subject ordered by subject and winner name; but list Chemistry and Physics last.

SELECT winner, subject
FROM nobel
WHERE yr=1984
ORDER BY subject IN (‘Chemistry’,‘Physics’), subject, winner
–要先保证’Chemistry’,'Physics’在后面,所以优先排序。

select within select

Using SELECT in SELECT
See SELECT FROM SELECT for how to use a derived table.
The result of a SELECT statement may be used as a value in another statement. For example the statement SELECT continent FROM world WHERE name = ‘Brazil’ evaluates to ‘South America’ so we can use this value to obtain a list of all countries in the same continent as ‘Brazil’
1.
List each country in the same continent as ‘Brazil’.

Alias

Some versions of SQL insist that you give the subquery an alias. Simply put AS somename after the closing bracket:
SELECT name FROM world WHERE continent =
(SELECT continent FROM world WHERE name=‘Brazil’) AS brazil_continent

Multiple Results

The subquery may return more than one result - if this happens the query above will fail as you are testing one value against more than one value. It is safer to use IN to cope with this possibility.
The phrase (SELECT continent FROM world WHERE name = ‘Brazil’ OR name=‘Mexico’) will return two values (‘North America’ and ‘South America’). You should use:
SELECT name, continent FROM world
WHERE continent IN
(SELECT continent FROM world WHERE name=‘Brazil’
OR name=‘Mexico’)
2.
List each country and its continent in the same continent as ‘Brazil’ or ‘Mexico’.

Subquery on the SELECT line

If you are certain that only one value will be returned you can use that query on the SELECT line.
3.
Show the population of China as a multiple of the population of the United Kingdom

Operators over a set

These operators are binary - they normally take two parameters:
= equals

greater than

< less than

= greater or equal
<= less or equal
You can use the words ALL or ANY where the right side of the operator might have multiple values.

Show each country that has a population greater than the population of ALL countries in Europe.
Note that we mean greater than every single country in Europe; not the combined population of Europe.

This tutorial looks at how we can use SELECT statements within SELECT statements to perform more complex queries.
name continent area population gdp
Afghanistan Asia 652230 25500100 20343000000
Albania Europe 28748 2831741 12960000000
Algeria Africa 2381741 37100000 188681000000
Andorra Europe 468 78115 3712000000
Angola Africa 1246700 20609294 100990000000

Tests

  1. List each country name where the population is larger than that of ‘Russia’.

SELECT name FROM world
WHERE population >
(SELECT population FROM world
WHERE name = ‘Russia’)

  1. Show the countries in Europe with a per capita GDP greater than ‘United Kingdom’.

SELECT name FROM world
WHERE continent = ‘Europe’ AND
gdp/population >
(SELECT gdp/population FROM world
WHERE name = ‘United Kingdom’)

  1. List the name and continent of countries in the continents containing either Argentina or Australia. Order by name of the country.

SELECT name, continent FROM world
WHERE continent IN
(SELECT continent FROM world
WHERE name IN (‘Argentina’, ‘Australia’))
ORDER BY name

  1. Which country has a population that is more than Canada but less than Poland? Show the name and the population.

SELECT name, population FROM world
WHERE population >
(SELECT population FROM world
WHERE name = ‘Canada’) AND
population < (SELECT population FROM world
WHERE name = ‘Poland’)

  1. Show the name and the population of each country in Europe. Show the population as a percentage of the population of Germany.

SELECT name,CONCAT(ROUND(population/
(SELECT population FROM world
WHERE name = ‘Germany’)*100, 0), ‘%’) FROM world
WHERE continent = ‘Europe’

  1. Which countries have a GDP greater than every country in Europe? [Give the name only.] (Some countries may have NULL gdp values)

SELECT name FROM world
WHERE gdp > ALL(SELECT gdp FROM world
WHERE continent = ‘Europe’ AND gdp > 0 )

  1. Find the largest country (by area) in each continent, show the continent, the name and the area:

SELECT continent, name, area FROM world x
WHERE x.area >=
ALL(SELECT area FROM world y
WHERE x.continent = y.continent
AND y.area > 0)

  1. List each continent and the name of the country that comes first alphabetically.

SELECT continent,name FROM world x
WHERE x.name=(SELECT name FROM world y
WHERE y.continent=x.continent ORDER BY name
LIMIT 1)

  1. Find the continents where all countries have a population <= 25000000. Then find the names of the countries associated with these continents. Show name, continent and population.

SELECT name, continent, population FROM world x
WHERE 25000000 >= ALL(SELECT population FROM world y
WHERE x.continent = y.continent
AND y.population > 0)

  1. Some countries have populations more than three times that of any of their neighbours (in the same continent). Give the countries and continents.

SELECT name, continent FROM world x
WHERE population/3 >= ALL(SELECT population FROM world y
WHERE x.continent = y.continent AND
x.name != y.name
AND y.population > 0)

Sum and count

Aggregates

The functions SUM, COUNT, MAX and AVG are “aggregates”, each may be applied to a numeric attribute resulting in a single row being returned by the query. (These functions are even more useful when used with the GROUP BY clause.)

Distinct

By default the result of a SELECT may contain duplicate rows. We can remove these duplicates using the DISTINCT key word.

Order by

ORDER BY permits us to see the result of a SELECT in any particular order. We may indicate ASC or DESC for ascending (smallest first, largest last) or descending order.
1.
The total population and GDP of Europe.

What are the regions?

Show the name and population for each country with a population of more than 100000000. Show countries in descending order of population.

World Country Profile: Aggregate functions

This tutorial is about aggregate functions such as COUNT, SUM and AVG. An aggregate function takes many values and delivers just one value. For example the function SUM would aggregate the values 2, 4 and 5 to deliver the single value 11.
name continent area population gdp
Afghanistan Asia 652230 25500100 20343000000
Albania Europe 28748 2831741 12960000000
Algeria Africa 2381741 37100000 188681000000
Andorra Europe 468 78115 3712000000
Angola Africa 1246700 20609294 100990000000

  1. Show the total population of the world.
    SELECT SUM(population) FROM world

  2. List all the continents - just once each.
    SELECT DISTINCT continent FROM world

  3. Give the total GDP of Africa
    SELECT SUM(gdp) FROM world
    WHERE continent = ‘Africa’

  4. How many countries have an area of at least 1000000
    SELECT COUNT(name) FROM world
    WHERE area >= 1000000

  5. What is the total population of (‘Estonia’, ‘Latvia’, ‘Lithuania’)
    SELECT SUM(population) FROM world
    WHERE name IN
    (‘Estonia’, ‘Latvia’, ‘Lithuania’)

  6. For each continent show the continent and number of countries.
    SELECT continent, COUNT(name) FROM world
    GROUP BY continent

  7. For each continent show the continent and number of countries with populations of at least 10 million.
    SELECT continent, COUNT(name) FROM world
    WHERE population > 10000000
    GROUP BY continent

  8. List the continents that have a total population of at least 100 million.
    SELECT continent FROM world
    GROUP BY continent
    HAVING SUM(population) >= 100000000
    总结:

  9. 注意理解WHERE,GROUP BY和HAVING的不同。

The JOIN operation

game
id mdate stadium team1 team2
1001 8 June 2012 National Stadium, Warsaw POL GRE
1002 8 June 2012 Stadion Miejski (Wroclaw) RUS CZE
1003 12 June 2012 Stadion Miejski (Wroclaw) GRE CZE
1004 12 June 2012 National Stadium, Warsaw POL RUS

goal
matchid teamid player gtime
1001 POL Robert Lewandowski 17
1001 GRE Dimitris Salpingidis 51
1002 RUS Alan Dzagoev 15
1002 RUS Roman Pavlyuchenko 82

eteam
id teamname coach
POL Poland Franciszek Smuda
RUS Russia Dick Advocaat
CZE Czech Republic Michal Bilek
GRE Greece Fernando Santos

JOIN and UEFA EURO 2012

This tutorial introduces JOIN which allows you to use data from two or more tables. The tables contain all matches and goals from UEFA EURO 2012 Football Championship in Poland and Ukraine.
The data is available (mysql format) at http://sqlzoo.net/euro2012.sql

  1. Modify it to show the matchid and player name for all goals scored by Germany. To identify German players, check for: teamid = ‘GER’.
    SELECT matchid, player FROM goal
    WHERE teamid = ‘GER’
  2. Show id, stadium, team1, team2 for just game 1012.
    SELECT id, stadium, team1, team2 FROM game
    WHERE id = 1012
  3. Modify it to show the player, teamid, stadium and mdate and for every German goal.
    SELECT goal.player, goal.teamid, game.stadium, game.mdate FROM goal
    JOIN game ON(id = matchid)
    WHERE teamid = ‘GER’
  4. Show the team1, team2 and player for every goal scored by a player called Mario player LIKE ‘Mario%’.
    SELECT game.team1, game.team2, goal.player FROM game
    JOIN goal ON (id = matchid)
    WHERE goal.player LIKE ‘Mario%’
  5. Show player, teamid, coach, gtime for all goals scored in the first 10 minutes gtime<=10
    SELECT goal.player, goal.teamid, eteam.coach, goal.gtime FROM goal
    JOIN eteam ON (teamid = id)
    WHERE gtime <= 10
  6. List the the dates of the matches and the name of the team in which ‘Fernando Santos’ was the team1 coach.
    SELECT game.mdate, eteam.teamname FROM game
    JOIN eteam ON(team1=eteam.id)
    WHERE coach = ‘Fernando Santos’
  7. List the player for every goal scored in a game where the stadium was ‘National Stadium, Warsaw’
    SELECT player FROM goal
    JOIN game ON(game.id = goal.matchid)
    WHERE stadium = ‘National Stadium, Warsaw’
  8. Instead show the name of all players who scored a goal against Germany.
    SELECT DISTINCT goal.player FROM goal
    JOIN game ON (game.id = matchid)
    WHERE (teamid != ‘GER’
    AND (team1=‘GER’ OR team2=‘GER’))
  9. Show teamname and the total number of goals scored.
    SELECT eteam.teamname, COUNT(goal.teamid) FROM eteam
    JOIN goal ON (teamid=eteam.id)
    GROUP BY teamname
  10. Show the stadium and the number of goals scored in each stadium.
    SELECT game.stadium, COUNT(player) FROM game
    JOIN goal ON (game.id = goal.matchid)
    GROUP BY stadium
  11. For every match involving ‘POL’, show the matchid, date and the number of goals scored.
    SELECT goal.matchid, game.mdate,COUNT(teamid) FROM goal
    JOIN game ON (game.id=matchid)
    WHERE (team1 = ‘POL’ OR team2 = ‘POL’)
    GROUP BY matchid, mdate
  12. For every match where ‘GER’ scored, show matchid, match date and the number of goals scored by ‘GER’
    SELECT goal.matchid, game.mdate, COUNT(teamid) FROM goal
    JOIN game ON (game.id=matchid)
    WHERE teamid = ‘GER’
    GROUP BY matchid, mdate
  13. List every match with the goals scored by each team as shown. This will use “CASE WHEN” which has not been explained in any previous exercises.
    SELECT game.mdate, game.team1,
    SUM(CASE WHEN teamid = team1 THEN 1 ELSE 0 END) AS score1,
    team2,
    SUM(CASE WHEN teamid = team2 THEN 1 ELSE 0 END) AS score2
    FROM game LEFT JOIN goal ON (game.id = matchid)
    GROUP BY mdate, matchid, team1, team2

More JOIN operations

This tutorial introduces the notion of a join. The database consists of three tables movie , actor and casting .
movie
id title yr director budget gross

actor
id name

casting
movieid actorid ord
SQLZOO学习笔记_第1张图片

Movie Database

This database features two entities (movies and actors) in a many-to-many relation. Each entity has its own table. A third table, casting , is used to link them. The relationship is many-to-many because each film features many actors and each actor has appeared in many films.

movie

Field name Type Notes
id INTEGER An arbitrary unique identifier
title CHAR(70) The name of the film - usually in the language of the first release.
yr DECIMAL(4) Year of first release.
director INT A reference to the actor table.
budget INTEGER How much the movie cost to make (in a variety of currencies unfortunately).
gross INTEGER How much the movie made at the box office.
Example
id title yr director budget gross
10003 “Crocodile” Dundee II 1988 38 15800000 239606210
10004 'Til There Was You 1997 49 10000000

actor

Field name Type Notes
id INTEGER An arbitrary unique identifier
name CHAR(36) The name of the actor (the term actor is used to refer to both male and female thesps.)
Example
id name
20 Paul Hogan
50 Jeanne Tripplehorn

casting

Field name Type Notes
movieid INTEGER A reference to the movie table.
actorid INTEGER A reference to the actor table.
ord INTEGER The ordinal position of the actor in the cast list. The
star of the movie will have ord value 1 the co-star will have
value 2, …
Example
movieid actorid ord
10003 20 4
10004 50 1

  1. List the films where the yr is 1962 [Show id, title]
    SELECT id, title
    FROM movie
    WHERE yr=1962
  2. Give year of ‘Citizen Kane’.
    SELECT yr
    FROM movie
    WHERE title = ‘Citizen Kane’
  3. List all of the Star Trek movies, include the id, titleand yr (all of these movies include the words Star Trek in the title). Order results by year.
    SELECT id, title, yr
    FROM movie
    WHERE title LIKE ‘Star Trek%’
    ORDER BY yr
  4. What id number does the actor ‘Glenn Close’ have?
    SELECT id
    FROM actor
    WHERE name = ‘Glenn Close’
  5. What is the id of the film ‘Casablanca’
    SELECT id
    FROM movie
    WHERE title = ‘Casablanca’
  6. Obtain the cast list for ‘Casablanca’.
    SELECT name
    FROM actor
    JOIN casting ON actor.id = casting.actorid
    JOIN movie ON movie.id = casting.movieid
    WHERE movie.id = 11768
  7. Obtain the cast list for the film ‘Alien’
    SELECT name
    FROM actor
    JOIN casting ON actor.id = casting.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 movie.id = casting.movieid
    JOIN actor ON actor.id = casting.actorid
    WHERE actor.name = ‘Harrison Ford’
  9. List the films where ‘Harrison Ford’ has appeared - but not in the starring role.
    SELECT DISTINCT title
    FROM movie
    JOIN casting ON movie.id = casting.movieid
    JOIN actor ON actor.id = casting.actorid
    WHERE actor.name = ‘Harrison Ford’
    AND casting.ord <> 1
  10. List the films together with the leading star for all 1962 films.
    SELECT title, 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
  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© 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 DISTINCT title, name
    FROM movie
    JOIN casting ON movie.id = casting.movieid
    JOIN actor ON actor.id = casting.actorid
    WHERE 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’)
    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
    WHERE casting.ord = 1
    GROUP BY name
    HAVING COUNT(name) >= 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 actor.id = casting.actorid
    JOIN movie ON movie.id = casting.movieid
    WHERE movie.id IN
    (SELECT movie.id
    FROM movie
    JOIN casting ON movie.id = casting.movieid
    JOIN actor ON actor.id = casting.actorid
    WHERE name = ‘Art Garfunkel’)
    AND name <> ‘Art Garfunkel’

你可能感兴趣的:(SQLZOO学习笔记)