postgresql 获取没有外键指向的行

cyej8jka  于 2022-12-23  发布在  PostgreSQL
关注(0)|答案(4)|浏览(142)

我有两张table

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)
)

以及

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
)

我想提出一个查询,仅当email_account中没有任何行指向city_url_id列时,才获取city_url中的行。

6jygbczu

6jygbczu1#

NOT EXISTS出现在脑海中:

select c.*
from city_url c
where not exists (select 1
                  from email_account ea
                  where ea.city_url_id = c.id
                 );
mrwjdhj3

mrwjdhj32#

还有这个选项:

SELECT city_url.*
FROM city_url
LEFT JOIN email_account ON email_account.city_url_id = city_url.id
WHERE email_account.id IS NULL
vbkedwbf

vbkedwbf3#

A NOT EXISTS绝对是“...如果没有行..."的答案。
尽管如此,通过选择差量来实现这一点将是优选的。
原则上是:

SELECT a.*  
FROM table1 a
LEFT JOIN table2 b
ON a.[columnX] = b.[columnY]
WHERE b.[columnY] IS NULL

使用这里的表名,这将是:

SELECT c.*
FROM city_url c
LEFT JOIN email_account e
ON c.id = e.city_url
WHERE e.city_url IS NULL
c9x0cxw0

c9x0cxw04#

我相信这里也可以使用NOT IN,尽管在大型数据集上可能性能较差:

SELECT * 
FROM city_url
WHERE id NOT IN (
  SELECT city_url_id FROM email_account
)

相关问题