Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 628
Moon Avatar asked May 07 '09 02:05

Moon


People also ask

How do you write a SQL query for many-to-many relationships?

When you need to establish a many-to-many relationship between two or more tables, the simplest way is to use a Junction Table. A Junction table in a database, also referred to as a Bridge table or Associative Table, bridges the tables together by referencing the primary keys of each data table.


2 Answers

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' 
like image 50
Andy White Avatar answered Oct 29 '22 17:10

Andy White


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 
like image 41
fesja Avatar answered Oct 29 '22 18:10

fesja