There are two answers that use the same method, but both are wrong. If this hypothetical database contains only a single movie per person, then it will work out. If there are multiple movies where a people
record is referenced, or if a single people
record is referenced by credits
joined to roles
records of roles
.role
= 'Director' or roles
.role
= 'Actor`, this query returns a record for that invalid result. This breaks the specified behavior.
Note that @Jason-Chen explains the issue you're experiencing with your query, while I'm specifically contradicting the two answers with solutions given as of the posting-time.
Instead of simply counting the results to guarantee more than one role per people.id, which is the only guarantee the above two examples give, the admin should instead query for a connection that exists both in the list of all roles records where 'Director' is the roles.role value and all records where 'Actor' is the roles.role value.
Note that I use different names below, because I generally find the practice of single-letter aliases to be awful, and I wish instructors would instill better practices in new students. Further, I find that table names in singular form yield the most readable code.
select `person`.*
from `people` `person`
where `person`.`id` in (
select `credit`.`person_id`
from `roles` `role`
join`credits` `credit`
on `role`.`id` = `credit`.`role_id`
where `role` like "Director"
) and `person`.`id` in (
select `credit`.`person_id`
from `roles` `role`
join`credits` `credit`
on `role`.`id` = `credit`.`role_id`
where `role` like "Actor"
);
I'm selecting a single value from both of the sub-queries on the roles table, which does not require an alias and instead behaves as a set. This results in very quick lookups, even for rather large tables, provided the keys used are indexed on both sides of the join.
Further, this is better than a join, because given real life examples like "Keanu Reaves", "Mel Gibson," "Tom Cruise," or other celebrities that have many Director/Actor movies under their belt, each such record would result in resultset magnification, where a single added record in data causes more than one resulting record.