列出外键关系中的问题

时间:2015-09-24 13:53:13

标签: sql foreign-key-relationship

我有两张桌子:

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查询,它列出了与另一个表断开关系的两个表的主键,即FOO s未在任何BARBAR个包含非法fooId的内容。在示例中,查询应返回:

fooId | barId
11      NULL
NULL    21

3 个答案:

答案 0 :(得分:2)

只需使用not exists(或not inleft join并附带where条款:

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

唯一已损坏的关系是bar.fooid与有效foo.id不匹配的关系。 <{1}}中的foo中没有相应值的值不会被破坏。

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

bar

答案 1 :(得分:0)

您可以使用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

答案 2 :(得分:0)

使用两个UNION ALL

进行NOT IN
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
相关问题