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 ?
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. 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
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.