首页 > 解决方案 > (SQL ZOO) 朱莉·安德鲁斯电影中的男主角

问题描述

SQL Zoo https://sqlzoo.net/wiki/More_JOIN_operations No. 12: 朱莉安德鲁斯电影的男主角 列出所有“朱莉安德鲁斯”出演的电影的片名和男主角。

你有没有得到“马克小小姐两次”?朱莉·安德鲁斯出演了 1980 年翻拍的马克小姐,而不是原版(1934 年)。

标题不是唯一字段,在您的子查询中创建一个 ID 表(这是什么意思?)

我写的是这个,但它说我错了,不知道为什么:

SELECT title, name 
FROM (movie JOIN casting ON movie.id = casting.movieid) JOIN actor ON actor.id = casting.actorid
WHERE title IN 
(SELECT title FROM casting JOIN actor ON casting.actorid = actor.id
where actor.name = 'Julie Andrews')
AND ord = 1

标签: sql

解决方案


WHERE title IN 
(SELECT title FROM casting JOIN actor ON casting.actorid = actor.id
where actor.name = 'Julie Andrews')

或中都没有title列。所以你不小心关联了这个子查询 - 标题的范围来自子查询之外,所以你实际上有类似的东西castingactor

where 1 in 
  (select 1 
   from casting JOIN actor ON casting.actorid = actor.id
   where actor.name = 'Julie Andrews'
  )

如果该子查询返回任何行,这将是真的。始终清楚列应该来自哪个行源。

您可能打算从中选择movieidcasting并将其用作movie.id与第一个子查询中的连接类似的过滤器:

SELECT movie.title, actor.name 
FROM movie 
JOIN casting ON movie.id = casting.movieid
JOIN actor ON actor.id = casting.actorid
WHERE movie.id IN 
(SELECT casting.movieId FROM casting JOIN actor ON casting.actorid = actor.id
where actor.name = 'Julie Andrews')
AND casting.ord = 1

推荐阅读