找到所有和Tom Hanks在同一部电影中演过的演员

时间:2017-02-15 22:01:00

标签: sql subquery inner-join

我有一个sql语句的开头,我应该找到所有与Tom Hanks在同一部电影中演过的演员。

select  a.name, m.title
from actor a 
inner join character c
inner join movie m

on a.id = c.actor_id
on c.movie_id = m.id

where a.name = 'Tom Hanks'

然而,这段代码只给了我汤姆汉克斯所扮演的电影的所有名字,但不是每个演员。

表格看起来像这样

Actor:
  ID
  name

  Primary Key: ID      

Character:
  Actor_ID
  Movie_ID
  Character

  Primary Key: (actor_id, movie_id, character)
  Foreign Key: actor_id references actor(id)
  Foreign Key: movie_id references movie(id)

Movie:
  ID
  Title
  Year
  Mpaa_rating
  Audience_score
  Critics_score

  Primary Key: ID

我一直在搞乱一些不同的子查询和内部联接,但似乎无法弄清楚我做错了什么。

2 个答案:

答案 0 :(得分:0)

为简单起见,分解为子查询

-- get all actors that are in movies that tom hanks is in
SELECT  * 
FROM    actor 
WHERE   
    actor_id IN 
    (   -- get all actor ids that are in movies that tom hanks is in
        SELECT  actor_id 
        FROM    character 
        WHERE   
            movie_id IN 
            (   -- get all movies that tom hanks is in
                SELECT  movie_id 
                FROM    character
                WHERE   
                    actor_id IN 
                    (   -- get actor ids that equal tom hanks
                        SELECT id 
                        FROM actor 
                        WHERE name = 'Tom Hanks'
                    )
            )
    )

答案 1 :(得分:0)

之前我犯了一个错误,需要一个" in"不是" =" 你也应该尝试这个:

Select a.name, m.title
From actor a, movie m, character c
Where a.id = c.actor_id
And m.id = c.movie_id
And m.id in ( select movie_id from character where actor_id = (select id from actor where name = 'the name'))