[英]how to find film title that have 2 actors in mysql?
Lets say this is my tables : 可以说这是我的桌子:
************
* film *
************
* title *
* film_id *
************
************
* actors *
************
* film_id *
* actor_id *
************
I would like to find the title of the film in which two actors participate actor_id = 22 and actor_id = 23
how to write the query ? 我想找到两个演员参与的电影的标题
actor_id = 22 and actor_id = 23
如何写查询?
I tried : 我试过了 :
SELECT title
FROM film
WHERE film_id IN(
SELECT film_id, COUNT(*)
FROM actors
WHERE actor_id=22 OR actor_id=23
GROUP BY film_id)
I believe the following query should make it for you. 我相信以下查询应该适合您。
SELECT title
FROM film f, actors a1, actors a2
WHERE f.film_id=a1.film_id AND a1.actor_id=22
AND f.film_id=a2.film_id AND a2.actor_id=23;
Joins are also a better way to handle it: 联接也是一种更好的处理方式:
SELECT title
FROM film f
JOIN actors a1 ON f.film_id = a1.film_id
JOIN actors a2 ON f.film_id = a2.film_id
WHERE a1.actor_id = 22
AND a2.actor_id = 23;
If you inner join to the actor table twice and set the individual actor_id
as criteria in each join it will require both actors to be in the film. 如果您两次内部连接到actor表,并在每个连接中将单独的
actor_id
设置为条件,则将要求两个actor都在电影中。 as a result you'll only return films that have both actors. 因此,您只会返回同时拥有两个演员的电影。
SELECT film.title
FROM film
INNER JOIN actors actors1
ON film.film_id = actors1.film_id
AND actors1.actor_id=22
INNER JOIN actors actors2
ON film.film_id = actors2.film_id
AND actors2.actor_id=23
GROUP BY film.title
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.