zoukankan      html  css  js  c++  java
  • SQL中in和not in

    参考:http://www.cnblogs.com/seasons1987/archive/2013/07/03/3169356.html

    今天遇到个问题,2W多条记录,使用in后是9k多,not in后竟然是空。就上网搜,就搜到了上面的连接,大概就是null值的原因吧!

    还是来测试吧,例子也和连接的类似。

    create table t1 (c1 int,c2 int);
    go
    create table t2 (c1 int,c2 int);
    go
    insert into t1 values(1,2),(1,3);
    go
    insert into t2 values(1,2);
    go
    image
    select * from t1
    where c2 in (select c2 from t2);
    image
    select * from t1
    where c2 not in (select c2 from t2);
    image
    再往t2表中插入一条记录
    insert into t2 values(1,null);
    再次查询
    select * from t1
    where c2 in (select c2 from t2);
    image
    问题来了哦,看下面查询
    select * from t1
    where c2 not in (select c2 from t2);
    image
    select * from t1
    where not exists (select c2 from t2 where t2.c2=t1.c2)
    image
    借用上文连接的那位仁兄的总结(直接ctrl+c,ctrl+v):

    如果子查询中返回的任意一条记录含有空值,则查询将不返回任何记录。如果子查询字段有非空限制,这时可以使用not in,并且可以通过提示让它用hasg_aj或merge_aj连接。

    如果查询语句使用了not in,那么对内外表都进行全表扫描,没有用到索引;而not exists的子查询依然能用到表上的索引。所以无论哪个表大,用not exists都比not in 要快。

  • 相关阅读:
    使用Spring AOP实现业务依赖解耦
    对Java提供的锁机制的一些思考
    关于数据库优化的一些想法
    漫谈使用Kafka作为MQ中间件
    数据库事务隔离引发的关于锁机制的思考
    使用Redis作为高速缓存
    Docker 构建映像
    Centos7 Nginx开机启动
    Docker 设置固定网络IP
    CentOS docker 常用命令
  • 原文地址:https://www.cnblogs.com/cnmarkao/p/4172057.html
Copyright © 2011-2022 走看看