Skip to content
Advertisement

how can I use two characters that are in the same column to limit my SELECT in SQL

i need to output all the movies that both “Johnny Depp” and “Helena Bonham Carter” starred. I think my problem is that I dont no what to putt inside of the WHERE

SELECT title
FROM movies JOIN
     stars
     ON movies.id = stars.movie_id JOIN
     people ON stars.person_id = people.id
WHERE

this is what I got so far…

Advertisement

Answer

I would recommend moving the where clause into a query from one of the tables as it will be more efficient. Suppose your people table has a field called name then you could do a subquery like so:

SELECT stars.movie_id, people.name
FROM stars
JOIN (SELECT id, name FROM people WHERE name="Johnny Depp") AS people
ON people.id = stars.people_id

This gives all Johnny Depp movies, a similar query gives all Helena Bonham Carter movies. Now you can intersect the two queries:

SELECT stars.movie_id, people.name
FROM stars
JOIN (SELECT id, name FROM people WHERE name="Johnny Depp") AS people
ON people.id = stars.people_id
WHERE movie_id IN (SELECT stars.movie_id, people.name
                   FROM stars
                   JOIN (SELECT id, name FROM people WHERE name="Helena Bonham Carter") AS people
                   ON people.id = stars.people_id)

This gives all movies starring both. Now intersect this with your original query

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement