【Mysql SQLZOO练习命令练习】

0、Select Basics 查询基础

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";

Select Basics
2.
Checking a list The word IN allows us to check if an item is in a list. The example shows the name and population for the countries ‘Brazil’, ‘Russia’, ‘India’ and ‘China’.

Show the name and the population for ‘Sweden’, ‘Norway’ and ‘Denmark’.

Select name,population From world 
Where name in ("Sweden","NorWay","Denmark");

在这里插入图片描述
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

在这里插入图片描述

1、SELECT names

You can use WHERE name LIKE ‘B%’ to find the countries that start with “B”.

The % is a wild-card it can match any characters
Find the country that start with Y

Select name From  world 
Where name LIKE 'Y%'

在这里插入图片描述

Find the countries that end with y

Select name From world 
Where name LIKE "%y"

在这里插入图片描述

Luxembourg has an x - so does one other country. List them both.

Find the countries that contain the letter x

SELECT name FROM world
  WHERE name LIKE '%x%'

在这里插入图片描述
4.
Iceland, Switzerland end with land - but are there others?

Find the countries that end with land

SELECT name FROM world
  WHERE name LIKE '%land'

在这里插入图片描述
5.
Columbia starts with a C and ends with ia - there are two more like this.

Find the countries that start with C and end with ia

SELECT name FROM world
  WHERE name LIKE 'C%ia'

在这里插入图片描述

Greece has a double e - who has a double o?

Find the country that has oo in the name

SELECT name FROM world
WHERE name LIKE "%oo%"

在这里插入图片描述
7.
Bahamas has three a - who else?

Find the countries that have three or more a in the name

SELECT name FROM world
  WHERE name LIKE '%a%a%a%'

在这里插入图片描述
8.
India and Angola have an n as the second character. You can use the underscore as a single character wildcard.

SELECT name FROM world
 WHERE name LIKE '_n%'
ORDER BY name

Find the countries that have “t” as the second character.

SELECT name FROM world
 WHERE name LIKE '_t%'
ORDER BY name

在这里插入图片描述
9.
Lesotho and Moldova both have two o characters separated by two other characters.

Find the countries that have two “o” characters separated by two others.

SELECT name FROM world
 WHERE name LIKE '%o__o%'

在这里插入图片描述
10.
Cuba and Togo have four characters names.

Find the countries that have exactly four characters.

SELECT name FROM world
 WHERE name LIKE '____'

在这里插入图片描述

The capital of Luxembourg is Luxembourg. Show all the countries where the capital is the same as the name of the country

Find the country where the name is the capital city.

SELECT name
  FROM world
 WHERE name = capital

在这里插入图片描述

The capital of Mexico is Mexico City. Show all the countries where the capital has the country together with the word “City”.
Find the country where the capital is the country plus “City”.

SELECT name FROM world
WHERE capital LIKE '_%City'
SELECT name FROM world
WHERE capital LIKE concat(name,' City')

在这里插入图片描述
13.
Find the capital and the name where the capital includes the name of the country.

Select capital,name FROM world
WHERE capital LIKE concat(name,'%')

在这里插入图片描述
14.
Find the capital and the name where the capital is an extension of name of the country.

You should include Mexico City as it is longer than Mexico. You should not include Luxembourg as the capital is the same as the country.

SELECT capital,name FROM world
WHERE capital LIKE concat(name,'%') AND capital != name;

在这里插入图片描述
15.
For Monaco-Ville the name is Monaco and the extension is -Ville.

Show the name and the extension where the capital is an extension of name of the country.

You can use the SQL function REPLACE.

In this example you remove all the 'a’s from the name of each country. This happens because the string ‘a’ is replaced with .

SELECT name,
       REPLACE(name, 'a','')
  FROM bbc

在这里插入图片描述

2、SELECT from WORLD Tutorial

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

在这里插入图片描述

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.

HELP:How to calculate per capita GDP
per capita GDP is the GDP divided by the population GDP/population

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 LIKE '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 (more than 3 million) or big by population (more than 250 million) but not both. Show name, population and area.

Australia has a big area but a small population, it should be included.
Indonesia has a big population but a small area, it should be included.
China has a big population and big area, it should be excluded.
United Kingdom has a small population and a small area, it should be excluded.

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.

For South America show population in millions and GDP in billions both to 2 decimal places.
Millions and billions

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,-3) 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.

You can use the LENGTH function to find the number of characters in a string

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.
You can use the function LEFT to isolate the first character.
You can use <> as the NOT EQUALS operator.

SELECT name,capital
FROM world 
WHERE name <> capital AND LEFT(name,1) = LEFT(capital,1)

在这里插入图片描述
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.

You can use the phrase name NOT LIKE ‘%a%’ to exclude characters from your results.
The query shown misses countries like Bahamas and Belarus because they contain at least one ‘a’

select name from world
where name LIKE '%a%' AND
name LIKE '%i%'AND
name LIKE '%e%'AND
name LIKE '%o%'AND
name LIKE '%u%'AND
name NOT LIKE '% %'

在这里插入图片描述

3、SELECT from Nobel Tutorial

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

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

在这里插入图片描述
2.
Show who won the 1962 prize for literature.

SELECT winner
  FROM nobel
 WHERE yr = 1962
   AND subject = 'literature'

在这里插入图片描述
3.
Show the year and subject that won ‘Albert Einstein’ his prize.

select yr,subject from nobel
where winner = 'Albert Einstein'

在这里插入图片描述

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

select winner from nobel 
where subject = 'peace' AND yr >= 2000

在这里插入图片描述
5.
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

在这里插入图片描述
6.
Show all details of the presidential winners:

Theodore Roosevelt
Thomas Woodrow Wilson
Jimmy Carter
Barack Obama

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

在这里插入图片描述
7.
Show the winners with first name John

select winner from nobel 
where winner LIKE 'John_%'

在这里插入图片描述
8.
Show the year, subject, and name of physics winners for 1980 together with the chemistry winners for 1984.

select yr,subject,winner from nobel 
where (yr=1980 AND subject ='physics') OR (yr=1984 AND subject='chemistry')

在这里插入图片描述
9.
Show the year, subject, and name of winners for 1980 excluding chemistry and medicine

select yr,subject,winner from nobel 
where yr=1980 AND subject NOT IN('chemistry','medicine')

在这里插入图片描述
10.
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 yr, subject, winner FROM nobel
WHERE (subject = 'Medicine' AND yr < 1910 )
	OR(subject ='Literature' and yr >= 2004);

在这里插入图片描述
11.
Find all details of the prize won by PETER GRÜNBERG

Non-ASCII characters

select * from nobel
where winner = 'PETER GRÜNBERG'

在这里插入图片描述
12.
Find all details of the prize won by EUGENE O’NEILL

Escaping single quotes
You can’t put a single quote in a quote string directly. You can use two single quotes within a quoted string.

select * from nobel
where winner = 'EUGENE O\'NEILL'

在这里插入图片描述
13.
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%'
//ODER BY yr DESC,winner

在这里插入图片描述

The expression subject IN (‘chemistry’,‘physics’) can be used as a value - it will be 0 or 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 ('physics','chemistry'),subject,winner

在这里插入图片描述

4、SELECT within SELECT Tutorial

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

world(name, continent, area, population, gdp)
SELECT name FROM world
  WHERE population >
     (SELECT population FROM world
      WHERE name='Russia')

在这里插入图片描述
2.
Show the countries in Europe with a per capita GDP greater than ‘United Kingdom’.

Per Capita GDP
The per capita GDP is the gdp/population

select name from world   where continent = 'Europe' AND 
GDP/population > (select gdp/population from world where
name  = 'United Kingdom')

在这里插入图片描述
3.

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

在这里插入图片描述
4.
Which country has a population that is more than United Kingom but less than Germany? Show the name and the population.

select name,population from world
where population >
(select population from world where name = 'United Kingdom' ) AND 
population < (select population from world where name = 'Germany' )

在这里插入图片描述
5.
Germany (population 80 million) has the largest population of the countries in Europe. Austria (population 8.5 million) has 11% of the population of Germany.

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

The format should be Name, Percentage for example:

name percentage
Albania 3%
Andorra 0%
Austria 11%
… …
Decimal places
Percent symbol %
You can use the function CONCAT to add the percentage symbol.

select name,CONCAT(ROUND(100*population/(select population from world where name = 'Germany'),0),'%') AS percentage from world where continent = 'Europe'

在这里插入图片描述
6.
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>(select MAX(GDP) from world where continent = 'Europe' AND GDP > 0)

在这里插入图片描述
7.
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 area >= ALL
 (select area from world y
   where y.continent = x.continent
AND area>0)

在这里插入图片描述
8.
List each continent and the name of the country that comes first alphabetically.

select w1.continent,w1.name from world w1 
where w1.name <=all(
select w2.name from world w2 
where w1.continent = w2.continent)

在这里插入图片描述
9.
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 w1.name,w1.continent,w1.population 
from world w1
where 25000000 >= (select MAX(w2.population) 
from world w2 where w1.continent = w2.continent 
group by w2.continent)

在这里插入图片描述
10.
Some countries have populations more than three times that of all of their neighbours (in the same continent). Give the countries and continents.

select w1.name,w1.continent from world w1 
where w1.population/3 >= ALL(select w2.population from world w2
where w1.continent =w2.continent AND w1.name != w2.name)

在这里插入图片描述

5、SUM and COUNT

Show the total population of the world.

world(name, continent, area, population, gdp)
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) AS COUNT from world where area >=1000000

在这里插入图片描述
5.
What is the total population of (‘Estonia’, ‘Latvia’, ‘Lithuania’)

select sum(population) AS ALLPOPULATION 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

在这里插入图片描述

6、The JOIN operation

The first example shows the goal scored by a player with the last name ‘Bender’. The * says to list all the columns in the table - a shorter way of saying matchid, teamid, player, gtime

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.
From the previous query you can see that Lars Bender’s scored a goal in game 1012. Now we want to know what teams were playing in that match.

Notice in the that the column matchid in the goal table corresponds to the id column in the game table. We can look up information about game 1012 by finding that row in the game table.

Show id, stadium, team1, team2 for just game 1012

select id,stadium,team1,team2 from game 
where id = '1012'

在这里插入图片描述
3.
You can combine the two steps into a single query with a JOIN.

SELECT *
  FROM game JOIN goal ON (id=matchid)

The FROM clause says to merge data from the goal table with that from the game table. The ON says how to figure out which rows in game go with which rows in goal - the matchid from goal must match id from game. (If we wanted to be more clear/specific we could say
ON (game.id=goal.matchid)

The code below shows the player (from the goal) and stadium name (from the game table) for every goal scored.

Modify it to show the player, teamid, stadium and mdate for every German goal.

SELECT player,teamid,stadium,mdate
  FROM game JOIN goal ON (id=matchid) AND teamid = 'GER'

在这里插入图片描述
4.
Use the same JOIN as in the previous question.

Show the team1, team2 and player for every goal scored by a player called Mario
player LIKE 'Mario%

select team1,team2,player from
game JOIN goal ON (id=matchid) where player LIKE 'Mario%'

在这里插入图片描述
5.
The table eteam gives details of every national team including the coach. You can JOIN goal to eteam using the phrase goal JOIN eteam on teamid=id

Show player, teamid, coach, gtime for all goals scored in the first 10 minutes gtime<=10

SELECT player, teamid, coach,gtime
  FROM goal JOIN eteam ON (teamid=id)
 WHERE gtime<=10

在这里插入图片描述
6.
To JOIN game with eteam you could use either
game JOIN eteam ON (team1=eteam.id) or game JOIN eteam ON (team2=eteam.id)

Notice that because id is a column name in both game and eteam you must specify eteam.id instead of just id

List the dates of the matches and the name of the team in which ‘Fernando Santos’ was the team1 coach.

select mdate,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 (matchid=id)
where stadium ='National Stadium, Warsaw'

在这里插入图片描述
8.
The example query shows all goals scored in the Germany-Greece quarterfinal.
Instead show the name of all players who scored a goal against Germany.

HINT
Select goals scored only by non-German players in matches where GER was the id of either team1 or team2. You can use teamid!='GER' to prevent listing German players. You can use DISTINCT to stop players being listed twice.

SELECT DISTINCT(player)
  FROM game JOIN goal ON (matchid = id )
    WHERE  teamid!='GER' AND (team1='GER'OR team2='GER')

在这里插入图片描述
9.
Show teamname and the total number of goals scored.
COUNT and GROUP BY
You should COUNT(*) in the SELECT line and GROUP BY teamname

select teamname,COUNT(matchid)
from eteam JOIN goal ON (id = teamid)
GROUP BY teamname

在这里插入图片描述
10.
Show the stadium and the number of goals scored in each stadium.

select stadium,COUNT(matchid)
from game JOIN goal ON (matchid=id)
GROUP BY stadium

在这里插入图片描述
11.
For every match involving ‘POL’, show the matchid, date and the number of goals scored.

SELECT matchid,mdate,COUNT(matchid)
  FROM game JOIN goal ON matchid = id 
 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 matchid,mdate,COUNT(matchid)
from game JOIN goal ON (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.
mdate team1 score1 team2 score2
1 July 2012 ESP 4 ITA 0
10 June 2012 ESP 1 ITA 1
10 June 2012 IRL 1 CRO 3

Notice in the query given every goal is listed. If it was a team1 goal then a 1 appears in score1, otherwise there is a 0. You could SUM this column to get a count of the goals scored by team1. Sort your result by mdate, matchid, team1 and team2.

SELECT mdate, 
team1,
SUM(CASE WHEN team1 = teamid THEN 1 ELSE 0 END) AS score1,
team2,
SUM(CASE WHEN team2 = teamid THEN 1 ELSE 0 END) AS score2
FROM game 
LEFT JOIN goal  ON id = matchid
GROUP BY mdate, team1,team2;
ORDER BY mdate, matchid, team1, team2;

在这里插入图片描述

7、More JOIN operations

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, title and 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’.

what is a cast list?
The cast list is the names of the actors who were in the movie.

Use movieid=11768, (or whatever value you got from the previous question)

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

在这里插入图片描述
7.
Obtain the cast list for the film ‘Alien’

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

在这里插入图片描述
8.
List the films in which ‘Harrison Ford’ has appeared

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

在这里插入图片描述
9.
List the films where ‘Harrison Ford’ has appeared - but not in the starring role. [Note: the ord field of casting gives the position of the actor. If ord=1 then this actor is in the starring role]

SELECT title FROM movie A
JOIN casting B ON (A.id = B.movieid)
JOIN actor C ON (C.id = B.actorid)
WHERE C.name = 'Harrison Ford' AND B.ord<>1

在这里插入图片描述
10.
List the films together with the leading star for all 1962 films.

SELECT M.title,A.name FROM casting C JOIN 
actor A ON (C.actorid = A.id) 
JOIN movie M ON (M.id  = C.movieid)
WHERE M.yr = '1962' AND C.ord  = '1'

在这里插入图片描述
11.
Which were the busiest years for ‘Rock Hudson’, 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(M.id)
FROM movie M 
JOIN casting C  ON (M.id=C.movieid)
JOIN actor A ON (A.id = C.actorid)
WHERE A.name = 'Rock Hudson'
GROUP BY yr
HAVING COUNT(M.id) >2;

在这里插入图片描述
12.
List the film title and the leading actor for all of the films ‘Julie Andrews’ played in.

Did you get “Little Miss Marker twice”?
Julie Andrews starred in the 1980 remake of Little Miss Marker and not the original(1934).

Title is not a unique field, create a table of IDs in your subquery

SELECT title,A.name FROM movie M 
JOIN casting C ON (M.id = C.movieid)
JOIN actor A ON (A.id = C.actorid)
WHERE  C.ord =1 AND 
M.id IN(SELECT CC.movieid 
FROM casting CC JOIN actor AA ON (AA.id = CC.actorid)
WHERE AA.name ='Julie Andrews')

在这里插入图片描述
13.
Obtain a list, in alphabetical order, of actors who’ve had at least 15 starring roles.

SELECT A.name FROM actor A
JOIN casting C ON (A.id = C.actorid) 
WHERE C.ord =1 
GROUP BY A.name
HAVING COUNT(C.movieid)>=15

在这里插入图片描述
14.
List the films released in the year 1978 ordered by the number of actors in the cast, then by title.

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

在这里插入图片描述
15.
List all the people who have worked with ‘Art Garfunkel’.

SELECT name 
FROM actor A
JOIN casting C ON (A.id = C.actorid)
WHERE name <>'Art Garfunkel' AND C.movieid IN (
SELECT movieid FROM casting WHERE actorid = (SELECT id FROM actor WHERE name = 'Art Garfunkel')
)

在这里插入图片描述

8、Using Null

List the teachers who have NULL for their department.

Why we cannot use =
You might think that the phrase dept=NULL would work here but it doesn’t - you can use the phrase dept IS NULL

That’s not a proper explanation.
No it’s not, but you can read a better explanation at Wikipedia:NULL.

SELECT name 
FROM teacher 
WHERE dept IS NULL;

在这里插入图片描述

Note the INNER JOIN misses the teachers with no department and the departments with no teacher.

SELECT teacher.name, dept.name
 FROM teacher INNER JOIN dept
           ON (teacher.dept=dept.id)

在这里插入图片描述

Use a different JOIN so that all teachers are listed.

SELECT Tec.name ,Dep.name
FROM teacher Tec 
LEFT JOIN dept Dep ON (Tec.dept = Dep.id)


在这里插入图片描述
4.
Use a different JOIN so that all departments are listed.

SELECT Tec.name ,Dep.name
FROM teacher Tec 
RIGHT JOIN dept Dep ON (Tec.dept = Dep.id)


在这里插入图片描述
5.
Use COALESCE to print the mobile number. Use the number ‘07986 444 2266’ if there is no number given. Show teacher name and mobile number or ‘07986 444 2266’

SELECT name,COALESCE(mobile,'07986 444 2266') AS mob 
FROM teacher

在这里插入图片描述
6.
Use the COALESCE function and a LEFT JOIN to print the teacher name and department name. Use the string ‘None’ where there is no department.

SELECT T.name, COALESCE(D.name,'None') AS departmentname
FROM teacher T
LEFT JOIN dept D ON (D.id =T.dept )

在这里插入图片描述7.
Use COUNT to show the number of teachers and the number of mobile phones.

SELECT COUNT(id),COUNT(mobile)
FROM teacher

在这里插入图片描述
8.
Use COUNT and GROUP BY dept.name to show each department and the number of staff. Use a RIGHT JOIN to ensure that the Engineering department is listed.

SELECT D.name,COUNT(T.id)
FROM teacher T 
RIGHT JOIN dept D ON (D.id = T.dept)
GROUP BY D.id,D.name

在这里插入图片描述
9.
Use CASE to show the name of each teacher followed by ‘Sci’ if the teacher is in dept 1 or 2 and ‘Art’ otherwise.

SELECT name,
CASE WHEN dept IN (1,2) THEN  'Sci'
	WHEN dept IS NULL THEN 'Art'
	ELSE 'Art'
	END
FROM teacher;

在这里插入图片描述
10.
Use CASE to show the name of each teacher followed by ‘Sci’ if the teacher is in dept 1 or 2, show ‘Art’ if the teacher’s dept is 3 and ‘None’ otherwise.

SELECT name,
CASE WHEN dept IN (1,2) THEN  'Sci'
	WHEN dept IS NULL THEN 'None'
	ELSE 'Art'
	END
FROM teacher;

在这里插入图片描述

9、Self join

How many stops are in the database.

SELECT COUNT(id) FROM stops;


在这里插入图片描述
2.
Find the id value for the stop ‘Craiglockhart’

SELECT id 
FROM stops 
WHERE name = 'Craiglockhart'

在这里插入图片描述
3.
Give the id and the name for the stops on the ‘4’ ‘LRT’ service.

SELECT S.id,S.name
FROM route R
JOIN stops S ON (S.id = R.stop)
WHERE R.num = '4' AND R.company = 'LRT';
SELECT id, name
FROM stops s
JOIN route r ON s.id = r.stop
WHERE num = '4' AND company = 'LRT';

在这里插入图片描述
4.
The query shown gives the number of routes that visit either London Road (149) or Craiglockhart (53). Run the query and notice the two services that link these stops have a count of 2. Add a HAVING clause to restrict the output to these two routes.

SELECT company, num, COUNT(*)
FROM route WHERE stop=149 OR stop=53
GROUP BY company, num
HAVING COUNT(*) = 2;

在这里插入图片描述
5.
Execute the self join shown and observe that b.stop gives all the places you can get to from Craiglockhart, without changing routes. Change the query so that it shows the services from Craiglockhart to London Road.

SELECT a.company, a.num, a.stop, b.stop
FROM route a JOIN route b ON
  (a.company=b.company AND a.num=b.num)
WHERE a.stop='53' AND b.stop = '149'

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值