Solution Practice Set 4
Get the solution to the exercise of viewing the information queried from a database.
We'll cover the following...
Solution Practice Set 4
The database relationship model is reprinted below for reference.
Connect to the terminal below by clicking in the widget. Once connected, the command line prompt will show up. Enter or copy and paste the command ./DataJek/Lessons/quiz.sh and wait for the MySQL prompt to start-up.
Question # 1
Write a query to display the average collection in millions of producers who have produced more than one movie.
To answer this question, we need to shortlist only those producers whose name appears more than once in the Movies table. This is hinting towards grouping the results by producers:
SELECT Producer
FROM Movies
GROUP BY Producer;
Since we are only interested in producers who have produced more than one movie, we will add a restriction on the number of times a producer’s name appears in the Movies table. The HAVING clause used with the GROUP BY clause will give us the desired result.
SELECT Producer
FROM Movies
GROUP BY Producer
HAVING COUNT(Producer) > 1;
We are now left with two produces who have multiple movies. The last step is to find the average collection in millions of the films by these two producers:
SELECT Producer AS Producer_Name, AVG(CollectionInMillions) AS Average_Collection_In_Millions
FROM Movies
GROUP BY Producer
HAVING COUNT(Producer) > 1;
Question # 2
Find all those actors who have not worked with producer Ryan Seacrest.
Approach 1: Joining three tables in a single SQL query.
The information on actors, movies and producers is scattered in three tables; Actors, Cast and Movies. We need to join the tables together to find the answer. Joining three tables in a single SQL query can be a tricky concept. The first table is related to the second table and the second table is related to the third table. In our case the Actors table is related to the Cast table and the Cast table is related to the Movies table. We want the names of the actors from the Actors table and information on producers from the Movies table.
The Cast table joins the two tables Actors and Movies together and contains the primary key of both tables. The primary key (PK) of the Actors table is a foreign key (FK) in the Cast table. Similarly, the primary key of the Movies table is the foreign key in the Cast table. Understanding these table relationships is the key to joining multiple tables in a single MySQL query.
The basic syntax of joining three tables in MySQL is as follows:
SELECT table1.col, table3.col ...