网站首页 文章专栏 in和exists, not in和not exists的区别

in和exists, not in和not exists的区别

编辑时间:2019-04-12 09:58:31 作者:苹果 浏览量:1563


    前言:in和exists,not in和not exists表达的意思差不多相同,但对于数据库查询效率的影响差距很大。


如果查询的两个表大小相当,那么用in和exists差别不大;如果两个表中一个较小一个较大,则子查询表大的用exists,子查询表小的用in;

select * from 表A where id in (select id from 表B)



上面sql语句相当于


select * from 表A where exists(select * from 表B where 表B.id=表A.id)



区分in和exists主要是造成了驱动顺序的改变(这是性能变化的关键),如果是exists,那么以外层表为驱动表,先被访问,如果是IN,那么先执行子查询。所以IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况。



关于not in和not exists,推荐使用not exists,不仅仅是效率问题,not in可能存在逻辑问题,如果你误用了not in,小心你的程序存在致命的BUG


原sql语句


select colname … from A表 where a.id not in (select b.id from B表)



高效的sql语句


select colname … from A表 Left join B表 on where a.id = b.id where b.id is null


取出的结果集为,A表不在B表中的数据


in 与 = 的区别  in可以理解为一堆or的集合

select name from student where name in('zhang','wang','zhao');

select name from student where name='zhang' or name='wang' or name='zhao'

的结果是相同的。



    出自:何冰华个人网站

    地址:https://www.hebinghua.com/

    转载请注明出处


来说两句吧
最新评论