获取没有外键指向的行

Ary*_*rya 8 sql postgresql

我有两张桌子

CREATE TABLE public.city_url
(
  id bigint NOT NULL DEFAULT nextval('city_url_id_seq'::regclass),
  url text,
  city text,
  state text,
  country text,
  common_name text,
  CONSTRAINT city_url_pkey PRIMARY KEY (id)
)
Run Code Online (Sandbox Code Playgroud)

CREATE TABLE public.email_account
(
  id bigint NOT NULL DEFAULT nextval('email_accounts_id_seq'::regclass),
  email text,
  password text,
  total_replied integer DEFAULT 0,
  last_accessed timestamp with time zone,
  enabled boolean NOT NULL DEFAULT true,
  deleted boolean NOT NULL DEFAULT false,
  city_url_id bigint,
  CONSTRAINT email_accounts_pkey PRIMARY KEY (id),
  CONSTRAINT email_account_city_url_id_fkey FOREIGN KEY (city_url_id)
      REFERENCES public.city_url (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
Run Code Online (Sandbox Code Playgroud)

我想提出一个查询,该查询city_url仅在 email_account 中没有用列指向它的行时才提取行city_url_id

Gor*_*off 8

NOT EXISTS 想到:

select c.*
from city_url c
where not exists (select 1
                  from email_account ea
                  where ea.city_url_id = c.id
                 );
Run Code Online (Sandbox Code Playgroud)