我有下面的电影数据库关系图,并使用下面的查询创建表及其键,如下所示:
以下是我用来创建这4个表并插入数据的代码:
CREATE TABLE my_movie
(movie_id int not null,
movie_name char(100) not null,
movie_released date not null,
primary key(movie_id))
CREATE TABLE person_name
(person_id int primary key,
first_name char(50)not null,
last_name char(50) not null,
birthdate date)
CREATE TABLE role
(role_id int primary key,
role_name char(50) not null)
CREATE TABLE movie_employee
(movie_id int not null,
person_id int not null,
role_id int not null,
primary key(movie_id, person_id, role_id),
FOREIGN KEY(movie_id) references my_movie(movie_id),
FOREIGN KEY(person_id) references person_name(person_id),
FOREIGN KEY(role_id) references role(role_id))
insert into role
VALUES(1, 'director');
insert into role
VALUES(2, 'actor');
insert into role
VALUES(3, 'actress');
insert into person_name
values(1, 'James', 'Cameron', '1954-8-16');
insert into person_name
values(2, 'Leonardo', 'DiCaprio');
insert into person_name
values(3, 'Kate', 'Winslet');
insert into person_name
values(4, 'Francis', 'Coppola');
insert into person_name
values(5, 'Marlon', 'Brando');
insert into person_name
values(6, 'Keanu', 'Reeves');
insert into person_name
values(7, 'Hugo', 'Weaving');
insert into my_movie
VALUES(1, 'Titanic', '1997-12-19');
insert into my_movie
VALUES(2, 'The Godfather', '1972-03-15');
insert into my_movie
VALUES(3, 'The Matrix', '1999-03-31');
insert into movie_employee,
VALUES(1, 1, 1);
insert into movie_employee
VALUES(1, 2, 2);
insert into movie_employee
VALUES(1, 3, 3);
insert into movie_employee
VALUES(2, 4, 1);
insert into movie_employee
VALUES(2, 5, 2);
insert into movie_employee
VALUES(3, 6, 2);
insert into movie_employee
VALUES(3, 7, 2);
下面是我的4 SELECT表插入数据后的插图:
表my_movies:
表格movie_employee:
表格movie_name:
表角色:
下面的连接查询给出了如下所示的结果:
SELECT movie_name, movie_released, (role_name || ': ' || first_name || ' ' || last_name)as "Cast & Crew"
from my_movie
inner join movie_employee on my_movie.movie_id=movie_employee.movie_id
inner join role on movie_employee.role_id = role.role_id
inner join person_name on movie_employee.person_id = person_name.person_id
从这个连接的表中,泰坦尼克号重复了3次,教父重复了两次,多次单独列出了演员和船员。
我希望Cast&Crew成员(导演,男演员,女演员)为同一部电影被连接到一行,像下面突出显示的连接表输出。我该怎么做?
2条答案
按热度按时间jhkqcmku1#
在
grouping
,sub-query
和string_agg()
函数的帮助下,下面可以给予你你想要的。注意,我不能在PostgreSQL
上测试查询,但它可以在Microsoft SQL Server
上工作。所以这是给予你一个想法如何实现你的要求。ajsxfq5m2#
这是我的尝试,似乎是你正在寻找的适当结果:
使用**string_agg()**来按movie_id分组。