子查询相关的优化

    通常会遇到如下情况的子查询:

    • NOT IN (SELECT ... FROM ...)
    • NOT EXISTS (SELECT ... FROM ...)
    • IN (SELECT ... FROM ..)
    • EXISTS (SELECT ... FROM ...)

    有时,子查询中包含了非子查询中的列,如 select * from t where t.a in (select * from t2 where t.b=t2.b) 中,子查询中的 t.b 不是子查询中的列,而是从子查询外面引入的列。这种子查询通常会被称为关联子查询,外部引入的列会被称为关联列,关联子查询相关的优化参见。本文主要关注不涉及关联列的子查询。

    对于这种情况,可以将 ALL 或者 ANYMAX 以及 MIN 来代替。不过由于在表为空时,MAX(EXPR) 以及 MIN(EXPR) 的结果会为 NULL,其表现形式和 EXPR 是有 NULL 值的结果一样。以及外部表达式结果为 NULL 时也会影响表达式的最终结果,因此这里完整的改写会是如下的形式:

    • t.id < all(select s.id from s) 会被改写为 t.id < min(s.id) and if(sum(s.id is null) != 0, null, true)
    • t.id < any (select s.id from s) 会被改写为 t.id < max(s.id) or if(sum(s.id is null) != 0, null, false)

    对于这种情况,当子查询中不同值的个数只有一种的话,那只要和这个值对比就即可。如果子查询中不同值的个数多于 1 个,那么必然会有不相等的情况出现。因此这样的子查询可以采取如下的改写手段:

    • select * from t where t.id != any (select s.id from s) 会被改写为 select t.* from t, (select s.id, count(distinct s.id) as cnt_distinct from s) where (t.id != s.id or cnt_distinct > 1)
    • select * from t where t.id = all (select s.id from s) 会被改写为 select t.* from t, (select s.id, count(distinct s.id) as cnt_distinct from s) where (t.id = s.id and cnt_distinct <= 1)

    对于这种情况,会将其 IN 的子查询改写为 SELECT ... FROM ... GROUP ... 的形式,然后将 IN 改写为普通的 JOIN 的形式。如 select * from t1 where t1.a in (select t2.a from t2) 会被改写为 select t1.* from t1, (select distinct(a) a from t2) t2 where t1.a = t2.a 的形式。同时这里的 DISTINCT 可以在 t2.a 具有 UNIQUE 属性时被自动消去。

    这个改写会在 IN 子查询相对较小,而外部查询相对较大时产生更好的执行性能。因为不经过改写的情况下,我们无法使用以 t2 为驱动表的 index join。同时这里的弊端便是,当改写删成的聚合无法被自动消去且 t2 表比较大时,反而会影响查询的性能。目前 TiDB 中使用 tidb_opt_insubq_to_join_and_agg 变量来控制这个优化的打开与否。当遇到不合适这个优化的情况可以手动关闭。