K
K
KarlGTA2019-07-07 01:49:36
PostgreSQL
KarlGTA, 2019-07-07 01:49:36

How to write a SQL query to filter movies by genre and country?

Hi everybody!
I have a movie database that has the following tables:

  • countries (code, name)
  • genres (id, name)
  • movies (id, title, description)
  • movie_genres (movie_id, genre_id)
  • movie_countries (movie_id, country_code)

Task:
It is necessary to select all films whose genres and countries are in a certain list.
For example, select films whose countries are "Russia" AND "Japan" + genres "Action" AND "Comedy" AND "Horror".
My solution :
SELECT m.*
FROM movies m
WHERE m.id IN (
  SELECT groupped_movies.id
  FROM (
         SELECT m.id,
                array_agg(mc.country_code) country_codes,
                array_agg(mg.genre_id)     genre_ids
         FROM movies m
                LEFT JOIN movie_countries mc on m.id = mc.movie_id
                LEFT JOIN movie_genres mg on m.id = mg.movie_id
         GROUP BY m.id
       ) groupped_movies
   WHERE groupped_movies.country_codes @> ARRAY ['ru', 'ja'] AND groupped_movies.genre_ids @> ARRAY [1, 2, 3]);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question