40

I found the following table structures while I was watching ruby on rails tutorial.

table actors
id  int  11  primary key auto_increment
name  varchar  30

table movies
id  int  11  primary key auto_increment
name  varchar  30

table actors_movies
actor_id  int  11
movie_id  int  11

How do I make a query to select movies that an actor is involved in?

I am not asking for ruby on rails code. I want the actual mysql query string.

Thank you!

Rowland
  • 1,728
  • 1
  • 12
  • 19
Moon
  • 22,195
  • 68
  • 188
  • 269
  • You may want to put your code sample in a code block - just put four spaces before each line of it, and put a blank line before and after the block. – bdonlan May 07 '09 at 02:07

4 Answers4

53

Maybe something like this:

select m.name
from movies m
inner join actors_movies am on m.id = am.movie_id
inner join actors a on am.actor_id = a.id
where a.name = 'Christopher Walken'
Andy White
  • 86,444
  • 48
  • 176
  • 211
  • Is there any way to get only movies with combination of actors like IN ('Christopher Walken', 'John Doe') @AndyWhite – mcek Jan 16 '19 at 12:57
  • 1
    @mcek you can do it using subqueries like this: [pasted code](https://pastebin.com/5P9bw9dD). Another way is a "Self Join": [pasted code](https://pastebin.com/mTCJAH40). But in both cases query will grow with the quantity of actors in combination. So they are not universal but can be auto generated. – chill appreciator Aug 29 '19 at 15:05
21

one thing to consider is that you are going to load the author object (because of RoR models), so with the ID would be enough:

select movies.id, movies.name
from movies inner join actors_movies
on actors_movies.movie_id=movies.id
where actors_movies.actor_id=$actor_id
fesja
  • 3,313
  • 6
  • 30
  • 42
10

Simple, just use the combined table to join the movie/actor tables:

Select m.name 
From actors a
Inner Join actors_movies am On am.actor_id = a.id
Inner Join movies m On m.id = am.movie_id
Where a.name = @your_actor
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
2
select m.* from movies m 
inner join actors_movies am on am.movie_id  = m.id 
inner join actors a on a.id = am.actor_id 
where a.someField = somevalue
razenha
  • 7,660
  • 6
  • 37
  • 53