Reputation: 25
I'm trying to find the film list where two actors are together in a particular film. The correct query to use is the following
select f.title from film f
INNER JOIN film_actor fa1 ON f.film_id = fa1.film_id
INNER JOIN film_actor fa2 ON f.film_id = fa2.film_id
INNER JOIN actor a1 ON a1.actor_id = fa1.actor_id
INNER JOIN actor a2 ON a2.actor_id = fa2.actor_id
where
(a1.first_name = 'CATE' and a1.last_name = 'MCQUEEN')
and
(a2.first_name = 'CUBA' and a2.last_name = 'BIRCH')
And the below method doesn't return any result:
select f.title from film f
INNER JOIN film_actor fa ON f.film_id = fa.film_id
INNER JOIN actor a1 ON a1.actor_id = fa.actor_id
INNER JOIN actor a2 ON a2.actor_id = fa.actor_id
where
(a1.first_name = 'CATE' and a1.last_name = 'MCQUEEN')
and
(a2.first_name = 'CUBA' and a2.last_name = 'BIRCH')
;
Can someone help me understand why?
Upvotes: 1
Views: 177
Reputation: 18002
In the second query by doing:
INNER JOIN actor a1 ON a1.actor_id = fa.actor_id
INNER JOIN actor a2 ON a2.actor_id = fa.actor_id
The actors a1 and a2 must be the same as they have the same id which is the value of fa.actor_id
.
So, then, this actor should also have:
first_name = 'CATE' and last_name = 'MCQUEEN'
and
first_name = 'CUBA' and last_name = 'BIRCH'
at the same time. Which can't happen.
That's why you need to join it twice with film_actor table so that a1 and a2 can be different.
Upvotes: 2