子查询和SQL连接

时间:2013-07-29 15:17:08

标签: sql select join inner-join

我正在解决以下问题,我必须“列出所有与'Art Garfunkel'合作过的人。”

问题是否定的。 16:http://sqlzoo.net/wiki/More_JOIN_operations

编辑:我编写了以下代码来获取整个名单,但是徒劳无功

select name 
from actor left join casting on id=actorid
where movieid IN ( select movieid
from casting left join actor on id=actorid
where id IN ( select id from actor where name ='Art Garfunkel'))

请告诉我哪里出错了?

3 个答案:

答案 0 :(得分:3)

试试这个:

SELECT a.name 
FROM actor a 
INNER JOIN casting b ON a.id = b.actorid 
INNER JOIN (SELECT b.movieid FROM casting b 
            INNER JOIN actor c ON b.actorid=c.id AND c.name = 'Art Garfunkel'
           ) c ON b.movieid = c.movieid 
where a.name <> 'Art Garfunkel';

答案 1 :(得分:0)

我认为您不需要任何子查询,只能使用JOINS来实现..

select distinct c1.name
from movie a 
inner join casting b on a.id=b.movieid
inner join actor c on b.actorid=c.id and c.name = 'Art Garfunkel'
inner join actor c1 on b.actorid=c.id and c.name <> 'Art Garfunkel'

答案 2 :(得分:0)

SELECT
   a.name
FROM
   actor a

   INNER JOIN casting c
   ON a.actorID = c.actorID
   AND a.actor <> 'Art Garfunkel'

WHERE
   c.movieID IN

(
SELECT
   m.movieID
FROM
   casting c

   INNER JOIN actor a
   ON c.actorID = a.actorID

   INNER JOIN movie m
   ON m.movieID = c.movieID

WHERE
   a.name = 'Art Garfunkel'
)