2015-07-02 169 views
0

我已經創建了數據庫這樣的:複雜的SQL查詢多對多

My database diagram

我想選擇的人,電影的名字是同一個人充當「Oyuncu」和「Senarist」

請幫幫我。我寫了一個這樣的查詢;

select 
    MovieName,PersonName,RoleName 
from 
    Movies, 
    MoviesPersonRole, 
    PersonRole, 
    Person, 
    Role 
where 
    Movies.Id = MoviesPersonRole.MovieId 
    and 
    PersonRole.Id = MoviesPersonRole.PersonRoleId 
    and 
    PersonRole.RoleId = Role.Id 
    and 
    PersonRole.PersonId = Person.Id 

,結果

MovieName   PersonName RoleName 
Pulp Fiction  Mehmet  Oyuncu 
Pulp Fiction  Mehmet  Senarist 
Matrix    Aylin   Oyuncu 
LOTR    Gökberk  Oyuncu 
LOTR    Gökberk  Senarist 
Pulp Fiction  Aylin   Oyuncu 
+0

什麼是數據庫引擎? –

+0

MSSQL服務器我的數據庫引擎 – MehmetF

+0

你的意思是同一個演員在做Oyuncu和Senarist角色? – jarlh

回答

2

你可以嘗試somethong這樣的:

SELECT X.MovieName, X.PersonName FROM (
    SELECT M.MovieName, PE.PersonName, COUNT(*) AS RoleCount 
    FROM Movies M 
    INNER JOIN MoviesPersonRole MPR ON (MPR.MovieId=M.Id) 
    INNER JOIN PersonRole PR ON (PR.Id = MPR.PersonRoleId) 
    INNER JOIN Person PE ON (PE.Id = PR.PersonId) 
    INNER JOIN Role R ON (R.Id = PR.RoleId) 
    WHERE R.RoleName='Oyuncu' OR R.RoleName='Senarist' 
    GROUP BY M.MovieName, PE.PersonName 
) X WHERE X.RoleCount>1 
+0

感謝兄弟。這對我來說是很好的:) – MehmetF

1

加入這一行查詢

and Role.RoleName in('Oyuncu' ,'Senarist') 
+0

我加了這一行和相同的結果。 我只想選擇誰扮演'Oyuncu'和'Senarist'的電影 – MehmetF

+0

不確定,但我懷疑OP是要求演員扮演Oyuncu和Senarist角色。 – jarlh

1

第二個加入的角色應該這樣做:

SELECT MovieName , 
     PersonName , 
     RoleName 
FROM Movies 
     JOIN MoviesPersonRole ON Movies.Id = MoviesPersonRole.MovieId 
     JOIN PersonRole ON PersonRole.Id = MoviesPersonRole.PersonRoleId 
     JOIN Person ON PersonRole.PersonId = Person.Id 
     JOIN Role Role1 ON PersonRole.RoleId = Role1.Id 
     JOIN Role Role2 ON PersonRole.RoleId = Role2.Id 
WHERE Role1.RoleName = 'Oyuncu' 
     AND Role2.RoleName = 'Senarist' 
+0

我們不能沒有聯接嗎?我們的表格之間的關係太多 – MehmetF

+0

您編寫的查詢也加入了表格,它只是使用了一種不同的(不贊成的)語法。 – NePh

0

以下查詢嘗試:

SELECT MovieName , 
     PersonName , 
     RoleName 
FROM Movies, 
     MoviesPersonRole, 
     PersonRole, 
     Person, 
     Role 
WHERE Role1.RoleName = 'Oyuncu' 
     AND Role2.RoleName = 'Senarist' 
     AND Movies.Id = MoviesPersonRole.MovieId 
     AND PersonRole.Id = MoviesPersonRole.PersonRoleId 
     AND PersonRole.RoleId = Role.Id 
     AND PersonRole.PersonId = Person.Id