【发布时间】:2021-06-29 23:29:52
【问题描述】:
我试图找出哪些人被认为是电影中的主要演员,但没有被记录为在该电影中扮演角色。
我的架构是:
CREATE TABLE public.movies (
id integer NOT NULL,
title text NOT NULL,
year_made public.yeartype NOT NULL,
runtime public.minutes,
rating double precision,
nvotes public.counter
);
CREATE TABLE public.people (
id integer NOT NULL,
name text NOT NULL,
year_born public.yeartype,
year_died public.yeartype
);
CREATE TABLE public.plays (
movie_id integer NOT NULL,
person_id integer NOT NULL,
"character" text NOT NULL
);
CREATE TABLE public.principals (
movie_id integer NOT NULL,
ordering public.counter NOT NULL,
person_id integer NOT NULL,
role text NOT NULL
到目前为止,我使用的查询适用于某些演员,但是我认为我的连接不正确,因为有另一个演员是主要演员,但被赋予了一个不应该有的角色(角色名称来自他们参演的另一部电影)。这是我的查询:
select name as actor, movies.title as movie,character
from principals
inner join people on principals.person_id=people.id
inner join movies on principals.movie_id=movies.id
left outer join plays on principals.person_id=plays.person_id
where principals.role = 'actor' and character is null
谁能帮我解决这个问题?
这是结果摘要,连接会将所有人物的角色名称添加到他们担任主角的每部电影中。
https://drive.google.com/file/d/1NVRLiYBVbKuiazynx9Egav7c4_VHFEzP/view?usp=sharing
【问题讨论】:
-
您可以使用
WHERE NOT EXISTS(... FROM plays WHERE ...)代替 LEFT JOIN(技术上是相同的,但实际上它更容易阅读/理解) -
sample数据不是数据库转储,从每个表中选择几行并将其作为插入提供或创建可用的小提琴。见Provide aMinimal Complete Verifiable Example(MCVE) 和Why should I provide a MCVE
标签: postgresql join null left-join