我正在尝试在MySQL中创建一个包含3个不同表格的视图。
CREATE TABLE ACTOR (
ACTOR_ID DECIMAL (2,0) PRIMARY KEY NOT NULL,
ACTOR_FIRST CHAR(25),
ACTOR_LAST CHAR(30),
DOB DATE
);
CREATE TABLE DIRECTOR (
DIRECTOR_ID DECIMAL(2,0) PRIMARY KEY NOT NULL,
DIRECTOR_FIRST CHAR(25),
DIRECTOR_LAST CHAR(30)
);
CREATE TABLE FILM (
FILM_ID DECIMAL(2,0) PRIMARY KEY NOT NULL,
TITLE CHAR(50),
RELEASE_DATE DATE,
DIRECTOR_ID DECIMAL(2,0),
GENRE_ID CHAR(10),
PRODUCTION_ID CHAR(3)
);
我试图创建的VIEW
:
create view film_production as
select
title,
actor_first,
actor_last,
director_first,
director_last,
Production_id,
release_date
from film,
actor,
director
;
这给了我192个结果。但我只有3个演员,8个电影,8个导演,6个production_id。另外需要注意的是1部电影中有3部演员中的2部,所以我应该至少有9部电影不能显示192部。我不知道自己做错了什么。我只是想不起来。我想的可能是join
或某种类型。
答案 0 :(得分:2)
是的,您的视图应该使用连接。
但是,看起来你错过了一张桌子,比如film_actor。 使用丢失的表格,并假设您正在尝试获取每部电影的演员和导演,这将是
SELECT
FILM.*
,ACTOR_FIRST + ' ' + ACTOR_LAST AS actor
,DIRECTOR_FIRST + ' ' + DIRECTOR_LAST AS director
FROM FILM
INNER JOIN FILM_ACTOR fa ON fa.FILM_ID = FILM.FILM_ID
INNER JOIN ACTOR ON ACTOR.ACTOR_ID = FILM_ACTOR.ACTOR_ID
INNER JOIN DIRECTOR d ON d.DIRECTOR_ID = FILM.DIRECTOR_ID
就像我提到的那样,你错过了一个能够容纳多个演员并将它们与一部电影相关联的表:一对多的关系。
答案 1 :(得分:1)
你有没有考虑在演员和电影,导演和电影表之间添加参考键?
<强>演员强>
CREATE TABLE ACTOR (
ID INT PRIMARY KEY NOT NULL,
FIRSTNAME VARCHAR(25),
LASTNAME VARCHAR(30),
DOB DATE
);
<强>总强>
CREATE TABLE DIRECTOR (
ID INT PRIMARY KEY NOT NULL,
FIRSTNAME VARCHAR(25),
LASTNAME VARCHAR(30)
);
与演员和导演有联系的电影
CREATE TABLE FILM (
FILM_ID INT PRIMARY KEY NOT NULL,
TITLE VARCHAR(50),
RELEASE_DATE DATE,
DIRECTOR_ID INT,
GENRE_ID INT,
PRODUCTION_ID INT,
ACTOR_ID INT,
CONSTRAINT FK_FILM_DIRECTOR_ID FOREIGN KEY (DIRECTOR_ID)
REFERENCES DIRECTOR(ID),
CONSTRAINT FK_FILM_ACTOR_ID FOREIGN KEY (ACTOR_ID)
REFERENCES ACTOR(ID)
);
查看合并3个表格
create view film_production as
select
title,
a.firstname as actor_firstname,
a.lastname as actor_lastname,
d.firstname as director_firstname,
d.lastname as directory_lastname,
Production_id,
release_date
from film f
left join actor a on f.actor_id = a.id
left join director d on f.director_id = d.id;
示例:http://sqlfiddle.com/#!9/9fe1e
请注意,对于ID字段和VARCHAR而不是CHAR字段,我使用了INT而不是DECIMAL。这可能有助于为大多数通用用途分配合适的空间。