列出外键关系中的问题

List problems in foreign key relations

我有两个表:

create table FOO (
    id integer primary key
);
create table BAR (
    id primary key,
    fooId integer -- yeah, this *should* be a foreign key
);
insert into FOO values (10);
insert into FOO values (11); -- no BAR
insert into BAR values (20, 10); -- OK
insert into BAR values (21, 3); -- No FOO
insert into BAR values (22, 10); -- duplicates are OK

出于某种原因,他们没有 FK 关系,尽管他们应该有。当我创建关系时,出现错误,因为某些关系已损坏。

我正在寻找一个 SQL 查询,它列出了两个表的主键,这些表与另一个表的关系是断开的,即 FOOs 没有在任何 BARs 和 BARs 其中包含非法的 fooIds。在示例中,查询应该 return:

fooId | barId
11      NULL
NULL    21

你可以使用 full outer join.

select foo.id as fooid, bar.id as barid
from foo
full join bar on foo.id = bar.fooid
where foo.id is null or bar.id is null

只需使用 not exists(或带有 where 子句的 not inleft join):

select b.*
from bar b
where not exists (select 1 from foo f where f.id = b.fooid);

唯一破裂的关系是bar.fooid与有效foo.id不匹配的关系。在 foo 中有一个值而在 bar 中没有相应的值并没有被破坏。

但要查找 foo.id 中未使用的值 bar,可以使用非常相似的查询:

select f.*
from foo f
where not exists (select 1 from bar b where f.id = b.fooid);

用两个 NOT IN 做一个 UNION ALL

select id, null from FOO where id not in (select fooId from bar where fooId is not null)
union all
select null, id from BAR where fooId not in (select id from foo where id is not null)

或者,FULL OUTER JOIN:

select distinct f.id, b.id
from foo f
  full outer join bar b on f.id = b.fooid
where f.id is null
   or b.id is null