I've made this SQLite code in the Movies exercise of Pset 7 from CS50 2020. It's the query number 12. The objective is to find all the movies in which both Helena Carter and Johnny Depp acted:
SELECT movies.title FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE movies.id IN (SELECT movies.id FROM movies WHERE name == "Helena Bonham Carter") AND movies.id IN (SELECT movies.id FROM movies WHERE name == "Johnny Depp");
But this code doesn't output anything. So I got some hints in Internet and wrote another code, that works correctly:
SELECT movies.title FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE movies.id IN (SELECT movies.id FROM movies WHERE name == "Helena Bonham Carter") AND movies.id IN (
SELECT movies.id FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE name == "Johnny Depp");
I'm still confused. If you take off the second condition of the first code, it works fine, and finds all the movies in which Helena Carter acted. Why did I have to JOIN tables again in order to make a second condition for Johnny Depp?
CodePudding user response:
Because each people
row has exactly one name. Therefore this phrase
SELECT movies.id FROM movies WHERE name == "Helena Bonham Carter")
AND movies.id IN (SELECT movies.id FROM movies WHERE name == "Johnny Depp"
will never return a result. (As will anything that tries to select name="a" AND name="b"
)