MySQL 如何查询多对多?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/832584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:14:06  来源:igfitidea点击:

how to query many-to-many?

mysqlmany-to-many

提问by Moon

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

我在看 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

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.

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

Thank you!

谢谢!

采纳答案by fesja

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:

需要考虑的一件事是您将要加载作者对象(由于 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

回答by Andy White

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'

回答by Justin Ethier

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

回答by razenha

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