我有一张 table :
sqlite> select * from lookup;
node|id
1|1
1|2
2|4
2|6
sqlite> select * from tag;
tagid|data
1|bar
2|baz
3|geek
4|foo
5|bank
6|auto
我想在标签表中找到查找中未引用的 id。 我尝试过:
select id from tag where not exists (select tagid from lookup);
# I am expecting the following result: 3, 5
但这没有返回任何内容。 tagid
是 tag
的外键,这可能是问题的根源吗?你能提示一下如何在 SQL 中执行此操作吗?
最佳答案
您需要关联两个查询。正如您所拥有的,您只是询问查找表中是否不存在任何内容。
select
id
from
tag t
where
not exists (
select
'x'
from
lookup l
where
l.tagid = t.id -- correlation
);
您还可以使用外部联接来编写此内容
select
t.id
from
tag t
left outer join
lookup l
on t.id = l.tagid
where
l.tagid is null;
某些数据库对于这两种方法具有不同的性能特征。
删除:
delete from
tag
where
not exists (
select
'x'
from
lookup l
where
l.tagid = tag.id
);
关于SQLite 两组之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25826715/