2011-04-18 293 views
2

考慮下面的SQL:爲什麼這個SQL查詢失敗?

SELECT mov 
FROM movie 
WHERE mov IN 
    (
     SELECT mov 
     FROM movie_star 
     GROUP BY(mov) 
     HAVING count(star) > 6 
    ) 
INNER JOIN movie_star 
ON movie_star.mov = movie.mov; 

我得到當執行此查詢以下錯誤:

.ERROR 1064(42000):你在你的SQL語法錯誤;檢查對應於你的MySQL服務器版本的權利 語法使用近「內部聯接上movie_star.mov = movie.mov movie_star」在行3

回答

5

WHEREJOIN有去 手冊條款。

SELECT movie.mov 
FROM movie 
INNER JOIN movie_star ON movie_star.mov = movie.mov 
WHERE mov IN (SELECT mov FROM movie_star GROUP BY mov HAVING COUNT(star) > 6); 
1

你在錯誤的地方有內連接。不確定當您僅​​選擇movie.mov列時,我發現完全需要內部連接,並且IN子句已確保movie_star中存在匹配的行。

select mov 
    from movie 
     inner join movie_star 
      on movie_star.mov = movie.mov 
    where mov in (select mov 
         from movie_star 
         group by(mov) 
         having count(star)>6); 
3

這裏的清理一點點相同的查詢:

select mov 
from movie 
where 
    mov in (select mov from movie_star group by(mov) having count(star) > 6) 
inner join movie_star on movie_star.mov = movie.mov 

因爲inner join出現在where條款後,當它應該from條款,而不是後立即出現在你有一個語法錯誤。

試試這個:

select mov 
from movie 
inner join movie_star on movie_star.mov = movie.mov 
group by mov 
having count(*) > 6 
+2

你的版本是最乾淨和自我解決,而使用IN的子選擇其他人已經離開了。 – DRapp 2011-04-18 19:05:41

+0

我同意,沒有子選擇,要好得多,但問題確實在問爲什麼它不起作用,因此其他答案不會以不同的方式做。好,但有人做了。 – Orbling 2011-04-18 23:07:34

1

,你必須參加,然後才能使用WHERE子句:

select mov from movie 
inner join movie_star on movie_star.mov = movie.mov 
where mov in 
(select mov from movie_star group by(mov) having count(star)>6)