V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
git00ll
V2EX  ›  MySQL

下面两种写法 not exist , 和 left join 哪个效率更优点

  •  
  •   git00ll · 2021-07-26 17:59:35 +08:00 · 840 次点击
    这是一个创建于 998 天前的主题,其中的信息可能已经有所发展或是发生改变。

    mysql,想要查询 [ txn_no 维度,a 表中存在但 b 表中不存在] 的数据

    方法 1,使用左连接,过滤掉右边为 null 的记录

    select a.id from 
    a 
    left join 
    b
    on a.txn_no = b.txn_no
    where b.txn_no is null
    
    

    方法 2,使用 not exist,过滤掉 b 表中有的记录

    
    select a.id from a where not exist
    ( select id from b where a.txn_no = b.txn_no )
    
    

    b 表的 txn_no 上有 btree 索引,

    从测试结果上两者执行时间差不多,从执行计划上来看,扫描的行数也是一样的,估计底层会将这两种写法优化成一样的执行计划?(猜测)

    那么哪种更优一点呢

    git00ll
        1
    git00ll  
    OP
       2021-07-26 18:18:49 +08:00
    看了一下书,这两种写法是会被优化成同样的执行计划的,并且第二种写法的可读性更高一点,所以我选择第二种了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1226 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 17:54 · PVG 01:54 · LAX 10:54 · JFK 13:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.