V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
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 · Jul 26, 2021 · 1396 views
    This topic created in 1735 days ago, the information mentioned may be changed or developed.

    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
       Jul 26, 2021
    看了一下书,这两种写法是会被优化成同样的执行计划的,并且第二种写法的可读性更高一点,所以我选择第二种了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5315 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 1294ms · UTC 01:18 · PVG 09:18 · LAX 18:18 · JFK 21:18
    ♥ Do have faith in what you're doing.