• 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 要快。

  • 相关阅读:
    QT 中如何实现一个简单的动画
    qt 中画线时如何设置笔的颜色和填充
    QT自定义窗口
    qt 中创建一个工作线程(例子)
    QT 获取系统时间
    火狐浏览器 system error code 1722 rpc服务器不可用和谷歌浏览器的插件application/x-print-ladop不支持
    ORA-10858:在要求输入数字处找到非数字字符
    eaeyui-combobox实现组合查询(即实现多个值得搜索)
    Mybatis中的模糊查询
    如何设置像我这样的博客的样式。
  • 原文地址:https://www.cnblogs.com/cnmarkao/p/4172057.html
Copyright © 2020-2023  润新知