创建视图问题

时间:2015-10-21 03:23:06

标签: sql

我需要创建一个视图,其中包含2010年发布的电影中的id和演员姓名。

我写了这个:

CREATE VIEW DRAMA_ACTORS 
AS 
    SELECT 
        ACTOR_ID, FIRST_NAME, LAST_NAME
    FROM 
        ACTOR, FILM_ACTOR, FILM, FILM_CATEGORY, CATEGORY
    WHERE 
        ACOTR.ACTOR_ID = FILM_ACTOR.ACTOR_ID
        AND FILM_ACTOR.FILM_ID = FILM.FILM_ID
        AND FILM.FILM_ID = FILM_CATEGORY.FILM_ID
        AND FILM_CATEGORY.CATEGORY_ID = CATEGORY.CATEGORY_ID
        AND CATEGORY.NAME = 'Drama'
        AND FILM.RELEASE_YEAR = '2010';

架构是这样的:

enter image description here

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您可能希望像这样使用JOIN

SELECT a.ACTOR_ID, a.FIRST_NAME, a.LAST_NAME
FROM FILM AS f
JOIN FILM_ACTOR AS fa ON fa.FILM_ID = f.FILM_ID
JOIN ACOTR AS a ON a.ACTOR_ID = fa.ACTOR_ID
JOIN FILM_CATEGORY AS fc ON fc.FILM_ID = f.FILM_ID
JOIN CATEGORY AS c ON c.CATEGORY_ID = fc.CATEGORY_ID
WHERE c.NAME = 'Drama' AND f.RELEASE_YEAR = '2010'

如果您获得了重复的结果,请在查询中使用DISTINCTGROUP BY

答案 1 :(得分:0)

最好(在我看来)避免首先创建重复项,而不是事后消除它们。

如果我们想要识别2010年参与过戏剧的演员,那么如果他们参与多部电影并不重要 - 我们只想宣称至少有一部这样的电影存在:

SELECT 
    ACTOR_ID, FIRST_NAME, LAST_NAME
FROM 
    ACTOR a
WHERE
    EXISTS (SELECT *
       FROM FILM_ACTOR fa
               INNER JOIN
            FILM f
               ON fa.FILM_ID = f.FILM_ID
               INNER JOIN
            FILM_CATEGORY fc
               ON
                  fc.FILE_ID = f.FILM_ID
               INNER JOIN
            CATEGORY c
               ON
                  fc.CATEGORY_ID = c.CATEGORY_ID
    WHERE
        a.ACTOR_ID = fa.ACTOR_ID
    AND c.NAME = 'Drama'
    AND f.RELEASE_YEAR = '2010'
);