美文网首页
mysql数据库优化 (一) in与not in

mysql数据库优化 (一) in与not in

作者: Java_Pro | 来源:发表于2018-09-17 11:48 被阅读0次

    场景

    查询一张表的数据是否存在于另一张表中
    第一写法就是用in或者not in
    例如

    select * from a where id in (select aid from b)
    

    优缺点

    • 直观
    • 效率低下(in会扫描全表)
    • 不适合大数据量

    解决办法

    1. 使用EXISTS代替IN
    select * from a where exists (select aid from b where a.id=b.aid)
    
    1. 使用左连接代替NOT IN,也可以用NOT EXISTS代替
    select * from a 
    left join b on a.id=b.aid
    where b.aid is null
    

    相关文章

      网友评论

          本文标题:mysql数据库优化 (一) in与not in

          本文链接:https://www.haomeiwen.com/subject/dyrknftx.html