【问题标题】: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都有相同的操作。

标签: database oracle url-rewriting cost-based-optimizer


【解决方案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.

【讨论】:

    猜你喜欢
    • 2018-12-20
    • 2011-09-25
    • 2021-11-14
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    相关资源
    最近更新 更多