SQLite两套之间的区别

时间:2014-09-13 19:13:42

标签: sql sqlite set

我有一张桌子:

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的foriegn密钥,这可能是问题的根源吗?您能否在SQL中提示如何执行此操作?

2 个答案:

答案 0 :(得分:2)

您需要关联这两个查询。如你所知,你只是询问查找表中是否存在任何内容。

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

答案 1 :(得分:0)

您从标记表中请求id,但您的select使用查找表中的ID。 您必须从标记表中选择tagid,以使这些标记不在查找表的ID集合中: 从标签中选择tagid,其中tagid不在(从查找中选择id);