目前我知道有两个办法,一个是not in, 另外一个是left join

大部分情况下,left join的效率比较高

1. 使用 not in 函数

EXPLAIN SELECT
	count(*) 
FROM
	( SELECT id FROM arg_approve WHERE create_time > '2020-08-13 00:00:00' ) a 
WHERE
	a.id NOT IN (
	SELECT
		approve_id 
	FROM
	arg_approve_query)

查看执行计划:
MySQL查看两个查询的差集

2. 使用left join

EXPLAIN SELECT
	a.session_hash,
	a.create_time,
	b.approve_id 
FROM
	( SELECT id, session_hash, create_time FROM arg_approve WHERE create_time > '2020-08-14 00:00:00' ) a
	LEFT JOIN arg_approve_query b ON a.id = b.approve_id 
WHERE
	approve_id IS NULL

查看执行计划:
MySQL查看两个查询的差集

3. 分析

首先可以看这篇文章构建一下基础
https://www.cnblogs.com/kongzhongqijing/articles/3544020.html

分析我们的执行计划,主要看索引类型和rows,使用left join的索引是ref,而not in使用的index。rows列很明显,外层扫描的rows行数,left join明显优于not in。

索引类型的效率关系:system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range > index > ALL

所以使用left join会比not in更加有效率。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-04
  • 2022-12-23
  • 2022-12-23
  • 2022-01-18
  • 2022-12-23
猜你喜欢
  • 2021-12-22
  • 2022-12-23
  • 2021-09-09
  • 2022-12-23
  • 2021-07-24
  • 2023-02-07
  • 2022-01-13
相关资源
相似解决方案