作为一项学习练习,您应该将查询分解为多个步骤。
步骤 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;