Moon
Moon

Reputation: 22565

how to query many-to-many?

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!

Upvotes: 40

Views: 55121

Answers (4)

Justin Ethier
Justin Ethier

Reputation: 134167

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

Upvotes: 10

razenha
razenha

Reputation: 7732

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

Upvotes: 2

fesja
fesja

Reputation: 3313

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

Upvotes: 21

Andy White
Andy White

Reputation: 88345

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'

Upvotes: 54

Related Questions