MySQL 8.0 新特性antijoin

MySQL 8.0.17版本引入了一个antijoin的优化,这个优化能够将where条件中的not in(subquery), not exists(subquery),in(subquery) is not true,exists(subquery) is not true,在内部转化成一个antijoin(反连接),以便移除里面的子查询subquery,这个优化在某些场景下,能够将性能提升20%左右。

原文地址:

https://mytecdb.com/blogDetail.php?id=108

1. antijoin适用场景

antijoin适用的场景案例通常如下:

  1. 找出在集合A且不在集合B中的数据
  2. 找出在当前季度里没有购买商品的客户
  3. 找出今年没有通过考试的学生
  4. 找出过去3年,某个医生的病人中没有进行医学检查的部分

上面这些场景,以第4个为例,转换成一个SQL,通常如下:

select * from patients where not exists( select * from exams where exams.type='check-up' and exams.date>=date_sub(now(), interval 3 year) and exams.patient_id=patients.patient_id );