SQL查询混淆 - 演员,角色,电影

时间:2014-12-01 09:45:21

标签: sql sql-server

我有三张桌子:

ACTOR

id 
nameofactor

MOVIE

id
nameOfmovie 

铸件

actorid 
movieid
role 

我想展示在电影中扮演多个角色的演员的名字

以下是我的尝试:

select 
    nameOfactor, nameOfmovie, CASTS.role
from 
    ACTOR, MOVIE, CASTS
where 
    ACTOR.id = CASTS.actorid 
    and CASTS.mid = MOVIE.movieid
group by 
    fname, lname, name, role
having 
    count(pid) >= 2; 

但它不起作用。

我想问题就是这样我必须把“角色”放在分组中,但是因为我需要展示角色,所以我必须要这个

我不知道如何修复此查询。如果有人可以提供帮助,我会很高兴

提前致谢

3 个答案:

答案 0 :(得分:5)

您需要生成具有多个角色的actor列表,然后使用该列表连接回您的表以获取角色。

首先获取具有多个角色的actor列表:

SELECT actorid, movieid
FROM CASTS
GROUP BY actorid, movieid
HAVING COUNT(*) > 1

现在您可以将其用作子查询,并JOIN将其用于其他表:

select nameOfactor, nameOfmovie, CASTS.role
from ACTOR
JOIN CASTS
    ON ACTOR.id=CASTS.actorid
JOIN MOVIE
    ON CASTS.mid=MOVIE.movieid
JOIN (SELECT actorid, movieid
      FROM CASTS
      GROUP BY actorid, movieid
      HAVING COUNT(*) > 1) A MultiRoles
    ON MultiRoles.actorid = CASTS.actorid 
    AND MultiRoles.movieid = CASTS.movieid

答案 1 :(得分:0)

select nameOfactor, nameOfmovie, count(role)
from ACTOR, MOVIE, CASTS
where ACTOR.id=CASTS.actorid and CASTS.movieid=MOVIE.id  
group by nameOfactor, nameOfmovie
having count(role)>1 ; 

答案 2 :(得分:0)

TRY THIS QUERY

--SAMPLE DATA SETUP

DECLARE @Actor TABLE
  (
     id          INT,
     nameofactor VARCHAR(50)
  )

INSERT INTO @Actor
SELECT 1,
       'Act-1'
UNION
SELECT 2,
       'Act-2'
UNION
SELECT 3,
       'Act-3'

DECLARE @MOVIE TABLE
  (
     id          INT,
     nameOfmovie VARCHAR(50)
  )

INSERT INTO @MOVIE
SELECT 1,
       'Mov-1'
UNION
SELECT 2,
       'Mov-2'
UNION
SELECT 3,
       'Mov-3'

DECLARE @CASTS TABLE
  (
     actorid INT,
     movieid INT,
     role    VARCHAR(50)
  )

INSERT INTO @CASTS
SELECT 1,
       1,
       'ROLE-1'
UNION
SELECT 2,
       2,
       'ROLE-2'
UNION
SELECT 1,
       1,
       'ROLE-3'
UNION
SELECT 2,
       2,
       'ROLE-4'
UNION
SELECT 3,
       3,
       'ROLE-5'


--SQL QUERY

SELECT A.*,
       (SELECT NAMEOFMOVIE
        FROM   @MOVIE
        WHERE  ID = B.movieid) NAMEOFMOVIE
FROM   @Actor A
       JOIN (SELECT MOVIEID,
                    ACTORID,
                    COUNT(ROLE) ROLECOUNT
             FROM   @CASTS
             GROUP  BY MOVIEID,
                       actorid
             HAVING COUNT(ROLE) > 1) B
         ON A.id = B.actorid