How do I list the first value from a three-way joi

2019-04-15 12:19发布

Ugh ok I'm terrible at explaining things, so I'll just give you the quotes and links first:

Problem 4b (near bottom):

4b. List the film title and the leading actor for all of 'Julie Andrews' films.

movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)
(Note: movie.id = casting.movieid, actor.id = casting.actorid)

My answer (doesn't work):
    SELECT title, name
      FROM casting JOIN movie
              ON casting.movieid = movie.id
      JOIN actor
              ON casting.actorid = actor.id
     WHERE name = 'Julie Andrews'
       AND ord = 1

The problem here is that it wants the list of lead actors of movies with 'Julie Andrews' as an actor (who is not necessarily the lead actor), but all I'm doing with my answer is getting the movies where she is the lead (ord = 1).

How do I specify the list of lead actors without 'Julie Andrews' being it? I suspect I have to do something with GROUP BY, but I can't figure out what at the moment...

Edit: Do I need to use a nested SELECT?

9条回答
趁早两清
2楼-- · 2019-04-15 13:09
SELECT title , name
FROM movie JOIN casting ON (casting.movieid=movie.id) JOIN actor ON (actor.id=actorid)
WHERE (movieid IN (SELECT movieid
FROM casting JOIN actor ON (actor.id=actorid)
WHERE name =  'Julie Andrews')) AND (ord=1)
查看更多
等我变得足够好
3楼-- · 2019-04-15 13:12
SELECT title, name
      FROM casting JOIN movie
              ON casting.movieid = movie.id
      JOIN actor
              ON casting.actorid = actor.id
     WHERE ord = 1
     and   casting.movieid in 
          (select movieid
           from   casting
                  join actor
                      on actor.id = casting.actorid
           where  actor.name = 'Julie Andrews')
查看更多
欢心
4楼-- · 2019-04-15 13:15
select title, name  from movie join casting on movie.id=movieid
join actor on actor.id=actorid 
where ord=1 and movieid in (select movieid from actor join casting 
                                            on actor.id=actorid 
         where name='julie andrews' and (ord=1 or ord<>1))group by title, name
查看更多
登录 后发表回答