如何查询多对多?

时间:2009-05-07 02:00:44

标签: mysql many-to-many

我在观看ruby on rails教程时发现了以下表结构。

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

如何查询选择参与者的电影?

我不是在rails代码上要求ruby。我想要实际的mysql查询字符串。

谢谢!

4 个答案:

答案 0 :(得分:37)

也许是这样的:

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'

答案 1 :(得分:17)

要考虑的一件事是你要加载作者对象(因为RoR模型),所以使用ID就足够了:

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

答案 2 :(得分:7)

简单,只需使用组合表来连接电影/演员表:

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

答案 3 :(得分: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