0

我在http://sqlzoo.net/wiki/Main_Page中练习 mysql 查询,遇到了这个关于连接的特定查询。问题:列出“朱莉·安德鲁斯”参演的所有电影的片名和男主角。表格结构:

movie   : id,title,yr,director,budget,gross -------
actor   :id,name ----------
casting :movieid,actorid,ord

提示:主要演员是演员表中 ord 为 1 的演员到目前为止我的回答:我可以获得所有电影“朱莉安德鲁斯”出演的电影 ID 和演员 ID。但使用该结果集,我不知道如何获取不同表中的标题和名称。

到目前为止我的查询:

select c1.actorid,c1.movieid 
from casting c1 
where c1.movieid in 
(
   select movieid from casting 
   join  actor on (id=actorid and name='Julie Andrews')
) and c1.ord=1
4

4 回答 4

0

作为一项学习练习,您应该将查询分解为多个步骤。

步骤 1. 列出电影片名

SELECT movie.title AS title
FROM movie

步骤 2. 列出 Julie Andrews 出演的电影:

SELECT movie.title AS title
FROM movie
JOIN casting
  ON movie.id = casting.movieid
JOIN actor
  ON casting.actorid = actor.id
WHERE actor.name = 'Julie Andrews'

步骤 3. 主要演员。在这里,您可以根据解决问题的方式开始不同的解决方案。

如果你想知道主要演员的名字。您的查询将如下所示:

SELECT actor.name as Name 
FROM casting
JOIN actor
  ON actor.id = casting.actorid
WHERE casting.ord =1

但是,如果您尝试这样做:

SELECT movie.title AS title
FROM movie
JOIN casting
  ON movie.id = casting.movieid
JOIN actor
  ON casting.actorid = actor.id
WHERE actor.name = 'Julie Andrews'
  AND casting.ord =1;

你只是在寻找朱莉安德鲁斯是主角的地方。

相反,您需要重新加入演员表(我将添加一些表别名,以帮助解释加入表的目的)

SELECT movie.title AS title, LeadActor.name AS LeadActorName
FROM movie
JOIN casting AS JulieCastings
  ON movie.id = JulieCastings.movieid
JOIN actor AS JulieAndrews
  ON JulieCastings.actorid = JulieAndrews.id
JOIN casting AS LeadActorCastings
  ON LeadActorCastings.movieid = movie.id
JOIN actor AS LeadActor
  ON LeadActor.id = LeadActorCastings.actorid
WHERE JulieAndrews.name = 'Julie Andrews'
  AND LeadActor.ord =1;
于 2013-10-15T12:32:29.780 回答
0

多谢你们。我已经通过以下查询解决了这个问题: select m.title,a.name from actor a join cast c on (a.id=c.actorid and c.ord=1) join movie m on ( m.id=c. movieid) 和 m.id in (select movieid from cast join actor on (id=actorid and name='Julie Andrews')

于 2013-10-16T11:33:50.633 回答
0

是的,你应该使用 join 代替:

      select c1.actorid, c1.movieid 
        join casting c2 on c2.movieid = c1.movieid
        join  actor a on a.id=c2.actorid
      from casting c1 
        where c1.ord=1 and
              a.name='Julie Andrews'
于 2013-10-15T12:36:39.303 回答
0

I know this is an old thread, but for anyone still looking for help like me, I worked off of Shankar's a bit and used this. Hope this helps.

SELECT title, name 
FROM movie JOIN casting ON (movie.id = casting.movieid) 
           JOIN actor ON (actor.id = casting.actorid)
WHERE movieid IN (SELECT movieid 
                  FROM casting JOIN actor ON (actor.id = casting.actorid)
                  WHERE name = 'Julie Andrews') 
                  AND ord = 1
于 2016-03-25T06:20:34.830 回答