Pregunta

I have a table (movies) with two foreign keys, (movie_id, genre_id). Of course, both fields aren't unique.

How do I select the movies that have two or more specific genres?

I want to do something like:

SELECT movie_id 
FROM movies
WHERE genre_id = 1 AND genre_id = 2 AND genre_id = 3
¿Fue útil?

Solución

This is a Relational Division problem.

SELECT movie_id 
FROM   movies
WHERE  genre_id IN (1, 2, 3)   -- <<== list of genre_id
GROUP  BY movie_id
HAVING COUNT(*) = 3            -- <<== count of genre_id

If genre_id is not unique for every movie_id, a DISTINCT keyword is needed to filter unique ones.

SELECT movie_id 
FROM   movies
WHERE  genre_id IN (1, 2, 3)             -- <<== list of genre_id
GROUP  BY movie_id
HAVING COUNT(DISTINCT genre_id) = 3      -- <<== count of genre_id

Otros consejos

This is an example of a "set-within-sets" query. I think the most general way is to put all the conditions in the having clause:

SELECT movie_id
FROM movies
group by movie_id
having sum(case when genre_id = 1 then 1 else 0 end) > 0 and
       sum(case when genre_id = 2 then 1 else 0 end) > 0 and
       sum(case when genre_id = 3 then 1 else 0 end) > 0;

Each of the clauses in the having clause is counting the number of records that match each type of genre.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top