2013-08-17 86 views
0

我試圖解決SQLzoo(http://sqlzoo.net/wiki/More_JOIN_operationsSQLzoo | JOIN操作

JOIN教程的問題13問的問題列出電影標題和所有的電影「朱莉·安德魯斯」中扮演的男主角。

我製作了下面的腳本,但是某處出錯了。

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

使用表的別名 –

回答

1

合適的劇本是:

SELECT m.title, 
     a.name 
FROM movie m 
     JOIN casting c 
     ON m.id = c.movieid 
      AND c.ord = 1 
     JOIN actor a 
     ON a.id = c.actorid 
WHERE m.id IN (SELECT m1.id 
       FROM movie m1 
         JOIN casting c1 
         ON m1.id = c1.movieid 
         JOIN actor a1 
         ON a1.id = c1.actorid 
       WHERE a1.name = 'Julie Andrews') 

我發現,如果我使用將m.title列作爲WHERE語句中的代理,腳本需要更多時間才能運行,並且SQLzoo服務器將其停止。相反,使用m.id列使得加載速度更快。也許是一個很好的習慣,如果可能的話,總是喜歡檢查數字而不是字母。

另一個問題上我最初的劇本中設定的等號操作代替。子查詢返回多於1行,因此需要使用IN運算符。

0

我認爲這是你得到它的正確方法。

SELECT m.title, a.name FROM 
    movie m JOIN casting c ON c.id = m.movieid 
     JOIN actor a ON a.id=m.actorid 
    WHERE m.ord=1 
    AND m.title = ALL 
     (SELECT m1.title FROM 
     movie m1 JOIN casting c1 ON c1.id=m1.movieid 
       JOIN actor a1 ON a1.id=m1.actorid 
      WHERE a1.name='Julie Andrews'); 

如果你有顯示與列名的表的話,我會修改這個查詢

1

試試這個:

SELECT title, name 
    FROM movie, casting, actor 
    WHERE movieid=movie.id 
    AND actorid=actor.id 
    AND ord=1 
    AND movieid IN 
    (SELECT movieid FROM casting, actor 
    WHERE actorid=actor.id 
    AND name='Julie Andrews') 
-1
SELECT title,name FROM 
casting join movie on movie.id=movieid and ord=1 
     join actor on actor.id=actorid 
WHERE movie.id in (
SELECT movie.id FROM 
movie join casting on movie.id=movieid 
     join actor on actor.id=actorid 
        WHERE name='Julie Andrews')