复杂的sql查询多对多

时间:2015-07-02 08:42:15

标签: sql sql-server tsql many-to-many

我已经创建了我的数据库:

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

4 个答案:

答案 0 :(得分:2)

你可以试试这样的事情:

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

答案 1 :(得分:1)

将此行添加到您的查询

$(function () {
    $("#tabs").tabs();

    if ($("#ListBoxPages").val() == null) {
        $("#tabs").css("display", "none");
    }

    $("#ListBoxPages").change(function () {
        $("#tabs").css("display", "block");
    });

});

答案 2 :(得分: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'

答案 3 :(得分: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