数据库中有几个表格:电影,人物和创作者。创作者对电影和人物有两个外键,以及“参与角色”(导演,演员,作曲家等)和“角色”字段(请参见下面的CREATE TABLE语句)。我想显示一个电影列表,其中导演同时扮演主要角色之一,指出他的姓氏和扮演的角色。
create table films (
film_id tinyint identity(1, 1),
film_name varchar(20) not null,
film_studio varchar(25) not null,
film_year int not null,
film_country varchar(20) null,
film_length tinyint not null,
film_genre varchar(15) not null,
constraint PK_films primary key(film_id),
);
create table persons (
person_id tinyint identity(1, 1),
person_name varchar(50) not null,
person_bday date not null,
person_dday date,
constraint PK_persons primary key(person_id),
);
create table creators (
creator_id tinyint identity(1, 1),
creator_film tinyint not null,
creator_person tinyint not null,
creator_who varchar(20) not null,
creator_role varchar(20),
constraint PK_creators primary key(creator_id),
constraint FK_CF foreign key(creator_film) references films(film_id),
constraint FK_CP foreign key(creator_person) references persons(person_id),
constraint CH_Who check(creator_who='director' or creator_who='actor' or creator_who='composer'),
);
insert into films(film_name, film_studio, film_year, film_country, film_length, film_genre) values ('Film1', 'Studio1', 2018, 'USA', 100, 'Genre1')
insert into films(film_name, film_studio, film_year, film_country, film_length, film_genre) values ('Film2', 'Studio2', 2018, 'USA', 120, 'Genre2')
insert into films(film_name, film_studio, film_year, film_country, film_length, film_genre) values ('Film3', 'Studio3', 2000, 'England', 90, 'Genre3')
insert into persons(person_name, person_bday, person_dday) values ('John Smitt', '1988-12-12', null)
insert into persons(person_name, person_bday, person_dday) values ('Mel Gibson
', '1988-12-12', null)
insert into persons(person_name, person_bday, person_dday) values ('Miley Cyrus', '2001-12-12', null)
insert into persons(person_name, person_bday, person_dday) values ('Deadpool', '1999-12-12', null)
insert into creators(creator_film, creator_person, creator_who) values (1, 1, 'Director')
insert into creators(creator_film, creator_person, creator_who, creator_role) values (1, 1, 'Actor', 'Main')
insert into creators(creator_film, creator_person, creator_who, creator_role) values (2, 3, 'Actor', 'Secondary')
insert into creators(creator_film, creator_person, creator_who, creator_role) values (3, 4, 'Actor', 'Secondary')
所需结果是:Film1 John Smith Main
答案 0 :(得分:0)
http://sqlfiddle.com/#!18/9211f/6
SELECT
films.film_name,
persons.person_name,
actor.creator_role
FROM creators director
INNER JOIN creators actor
ON director.creator_person = actor.creator_person
AND actor.creator_who = 'Actor'
LEFT JOIN films
ON director.creator_film = films.film_id
LEFT JOIN persons
ON director.creator_person = persons.person_id
WHERE director.creator_who = 'Director'