简体   繁体   中英

SQL select on a many-to-many table

I've got 3 tables: Movies , Actors , and MovieActors . MovieActors is a many-to-many relationship of Movies and Actors with columns MovieActorId , MovieId , and ActorId

How do I find movies that have a certain set of actors in it? For example I want to find all movies that have both Michael Fassbender (actor Id 1) and Brad Pitt (actor Id 2) in them. What would the query look like?

One way is to join the tables. Filter for the actors and then insure the count has the number of actors you want in it (2 in this case)

SELECT 
   m.MovieID
FROM
    Movies m
    INNER JOIN MovieActors ma
    ON m.MovieID = ma.MovieID

WHERE
    ma.ActorID IN (1,2)
GROUP BY 
   m.MovieID
HAVING COUNT(DISTINCT ma.ActorID) = 2 

DEMO

Note

Thanks to user814064 for pointing out that since Actors can have more than one role on a movie we need to count the DISTINCT ma.ActorID not just * The SQL Fiddle Demo demonstrates the difference

select m.movieid
from movies m
inner join movieactors ma on ma.movieid = m.movieid
where ma.actorid in (1,2)
group by m.movieid
having count(distinct ma.actorid) = 2

To keep it simple, you can just do two in clauses:

select * from Movies m
where m.MovieId in (select MovieId from MovieActors where ActorId = 1)
and m.MovieId in (select MovieId from MovieActors where ActorId = 2)

Performance may not be as good as a single join , but it's clean and easy to read.

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