[英]SQL select on a many-to-many table
I've got 3 tables: Movies
, Actors
, and MovieActors
. 我有3张桌子:
Movies
, Actors
和MovieActors
。 MovieActors
is a many-to-many relationship of Movies
and Actors
with columns MovieActorId
, MovieId
, and ActorId
MovieActors
是Movies
和Actors
的多对多关系,其MovieActorId
, MovieId
和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.
例如,我要查找所有同时具有Michael Fassbender(演员ID 1)和Brad Pitt(演员ID 2)的电影。 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)
筛选演员,然后确保人数中有您想要的演员人数(本例中为2)
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
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 感谢user814064指出,由于Actors在电影中可以扮演多个角色,因此我们需要计算
DISTINCT ma.ActorID
不仅*
SQL Fiddle Demo演示了区别
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: 为简单起见,您可以执行以下两个
in
子句:
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. 性能可能不如单个
join
,但是它很干净而且易于阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.