简体   繁体   中英

SQL Excercise (movies with number of actors)

I am doing a SQL exercise with the task: Output all movies involving more than 9 actors. Specify the number of actors as well, sort by Number_Actors in ascending order, and then by movie title. Projection list: Film_Id, film title, Number_Actors. Unfortunately, I am stuck and don't know what I made wrong.

SELECT film_id, title, COUNT(film_id) AS number_actors 
FROM (
   SELECT film.title
   FROM film
   INNER JOIN film ON film_actor.film_id = film.film_id
   WHERE number_actors > 9
)
GROUP BY number_actors
ORDER BY number_actors, film

以film_id为主键的表film

Tablefilm_actor,连接tablefilm和actor

表actor,以actor_id为主键

You can get the number of actors of each film by aggregation in the table film_actor .
If you also set the condition ...involving more than 9 actors in the HAVING clause then you get only the ids of the films that you want:

SELECT film_id, COUNT(*) Number_Actors
FROM film_actor
GROUP BY film_id
HAVING COUNT(*) > 9

You can join the table film to the above query:

SELECT f.film_id, f.title, t.Number_Actors
FROM film f
INNER JOIN (
    SELECT film_id, COUNT(*) Number_Actors
    FROM film_actor
    GROUP BY film_id
    HAVING COUNT(*) > 9
) t ON t.film_id = f.film_id
ORDER BY t.Number_Actors, f.title

It can be done even without a JOIN :

SELECT * FROM (
 SELECT film_id, title, 
       (SELECT COUNT(*) FROM film_actor Where film_id=f.film_id) number_actors 
 FROM film f ) f2
WHERE number_actors>9 ORDER BY number_actors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM