SQLite 两组之间的差异

标签 sql sqlite set

我有一张 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

但这没有返回任何内容。 tagidtag 的外键,这可能是问题的根源吗?你能提示一下如何在 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/

相关文章:

javascript - 如何使用 JavaScript get 和 set 进行 polyfill

sql - 删除oracle结果列之间的差距

mysql - 无法为行缓冲区列分配 1073741824 字节

python - 如何在Sqlite中删除记录

vb.net - SQLite 数据库文件放在网络文件夹中时无法打开

android - 在 SQLite 数据库上检索数据时出错

c++从另外两个集合形成集合

javascript - 为 Set 数据结构创建元素时,使用 '.has' 和不使用 '.has' 的性能如何?

sql - 按照与 XML 相同的顺序将 XML 元素插入 SQL 表中?

sql - 检查以前的记录以更新 Oracle 中的当前记录