“不在”和“不存在”有啥区别?
Posted
技术标签:
【中文标题】“不在”和“不存在”有啥区别?【英文标题】:what's the difference of 'not in' and 'not exists'?“不在”和“不存在”有什么区别? 【发布时间】:2020-12-17 10:36:18 【问题描述】:sql1: select * from t1 where not exists (select a from t2 where t2.a = t1.a);
sql2: select * from t1 where t1.a not in (select a from t2 where t2.a is not null);
我觉得sql1和sql2一样,都会改写成anti join吧?
【问题讨论】:
mysql 还是 oracle?请仅标记您正在使用的一个数据库。 我认为mysql和oracle都有相同的操作。 【参考方案1】:如果您有 NULL
值,这两个查询将给出不同的结果。
Oracle 中的示例:
create table t1 (a integer);
insert into t1 (a) values (1);
insert into t1 (a) values (2);
insert into t1 (a) values (null);
commit;
create table t2 (a integer);
insert into t2 (a) values (1);
insert into t2 (a) values (3);
insert into t2 (a) values (null);
commit;
set null "NULL"
prompt First Query...
select * from t1 where not exists (select a from t2 where t2.a = t1.a);
prompt Second Query...
select * from t1 where t1.a not in (select a from t2 where t2.a is not null);
输出:
First Query...
A
----------
2
NULL
2 rows selected.
Second Query...
A
----------
2
1 row selected.
【讨论】:
以上是关于“不在”和“不存在”有啥区别?的主要内容,如果未能解决你的问题,请参考以下文章