2012-11-07 49 views
0

這是我的代碼,稍後我將把它放到php中,但暫時我在提供的Query測試程序中使用它。我們正在做凱文培根的第一度,而不是第六度。獲取只在SQL中出現的相同結果

我的查詢如下:

SELECT name,year 
FROM actors 
JOIN roles ON roles.actor_id = actors.id 
JOIN movies ON movies.id=roles.movie_id 
WHERE actors.first_name= 'kevin' AND actors.last_name='bacon' OR actors.first_name= 'sean' AND actors.last_name='penn' 
ORDER BY movies.name; 

它導致

Animal House 1978 
Apollo 13 1995 
Few Good Men, A 1992 
Footloose 1984 
Hollow Man 2000 
JFK 1991 
Mystic River 2003 
Mystic River 2003 
Planes, Trains & Automobiles 1987 
Stir of Echoes 1999 

我如何得到它顯示只有神祕河?

+1

你想知道Kevin Bacon和Sean Penn在同一部電影中的位置嗎? – JoeFletch

回答

0

試試這個

SELECT DISTINCT name,year 
FROM actors 
JOIN roles ON roles.actor_id = actors.id 
JOIN movies ON movies.id=roles.movie_id 
WHERE actors.first_name= 'kevin' AND actors.last_name='bacon' OR actors.first_name= 'sean' AND actors.last_name='penn' 
ORDER BY movies.name; 
1

首先,組條件

WHERE (actors.first_name= 'kevin' AND actors.last_name='bacon') OR 
     (actors.first_name= 'sean' AND actors.last_name='penn') 

其次,添加DISTINCTSELECT關鍵字後

SELECT DISTINCT ... 

後續問題:爲什麼你繼續想要顯示Mystic River

1

我想你問這裏笏是DISTINCT ...

DISTINCT關鍵字可用於返回唯一不同的(不同的)值。

試試這個

SELECT DISTINCT name,year 
FROM actors 
JOIN roles ON roles.actor_id = actors.id 
JOIN movies ON movies.id=roles.movie_id 
WHERE (actors.first_name= 'kevin' AND actors.last_name='bacon') OR (actors.first_name= 'sean' AND actors.last_name='penn') 
ORDER BY movies.name; 

這where子句中,

WHERE (actors.first_name= 'kevin' AND actors.last_name='bacon') AND (actors.first_name= 'sean' AND actors.last_name='penn') 

,如果你想知道在哪裏都凱文·培根和西恩·潘是在同一部電影

1

如果我沒有理解你的問題正確,你正試圖找到其中有Sean PennKevin Bacon的電影列表。如果是這樣,那麼您需要在查詢中兩次使用actors和roles表。

SELECT 
    movies.name, 
    movies.year 
FROM 
    actors AS actor2 INNER JOIN roles AS role2 ON actor2.ID = role2.actor_id 
      INNER JOIN actors AS actor1 INNER JOIN roles AS role1 ON actor1.ID = role1.actor_id 
       INNER JOIN movies ON role1.movie_id = movies.ID ON role2.movie_id = movies.ID 
WHERE 
    actor1.first_name= 'kevin' AND actor1.last_name='bacon' 
     AND 
    actor2.first_name= 'sean' AND actor2.last_name='penn' 
ORDER BY movies.name;