有依赖关系的子查询是指该子查询的执行依赖了外部查询的“变量”,所以这种子查询通常会被计算多次。

    如下分别为没有依赖关系的子查询和有依赖关系的子查询的示例。

    如下分别为被改写成连接语句的子查询和没有被改写成连接语句的子查询的示例。

    1. Query OK, 0 rows affected (0.70 sec)
    2. OceanBase (root@test)> create table t2(a int primary key, b int, c int);
    3. Query OK, 0 rows affected (0.92 sec)
    4. -- 有依赖关系的子查询被改写成了semi-join,并且使用了hash semi-join来实现
    5. OceanBase (root@test)> explain select * from t1 where t1.a in (select t2.c from t2 where t2.b = t1.b);
    6. | =======================================
    7. |ID|OPERATOR |NAME|EST. ROWS|COST|
    8. ---------------------------------------
    9. |0 |HASH SEMI JOIN| |1 |2924|
    10. |1 | TABLE SCAN |t1 |1000 |455 |
    11. |2 | TABLE SCAN |t2 |1000 |455 |
    12. =======================================
    13. -------------------------------------
    14. 0 - output([t1.a], [t1.b], [t1.c]), filter(nil),
    15. equal_conds([t1.a = t2.c], [t2.b = t1.b]), other_conds(nil)
    16. 1 - output([t1.b], [t1.a], [t1.c]), filter(nil),
    17. access([t1.b], [t1.a], [t1.c]), partitions(p0)
    18. 2 - output([t2.b], [t2.c]), filter(nil),
    19. access([t2.b], [t2.c]), partitions(p0)
    20. -- 有依赖关系的子查询不能被改写成semi-join,使用了subplan filter来实现
    21. OceanBase (root@test)> explain select * from t1 where t1.a > (select sum(t2.c) from t2 where t2.b = t1.b);
    22. |ID|OPERATOR |NAME|EST. ROWS|COST |
    23. -------------------------------------------
    24. |0 |SUBPLAN FILTER | |334 |207683|
    25. |1 | TABLE SCAN |t1 |334 |176 |
    26. |3 | TABLE SCAN |t2 |2 |622 |
    27. ===========================================
    28. Outputs & filters:
    29. -------------------------------------
    30. 0 - output([t1.a], [t1.b], [t1.c]), filter([t1.a > subquery(1)]),
    31. exec_params_([t1.b]), onetime_exprs_(nil), init_plan_idxs_(nil)
    32. 1 - output([t1.b], [t1.a], [t1.c]), filter(nil),
    33. access([t1.b], [t1.a], [t1.c]), partitions(p0)
    34. 2 - output([T_FUN_SUM(t2.c)]), filter(nil),
    35. group(nil), agg_func([T_FUN_SUM(t2.c)])
    36. 3 - output([t2.c]), filter([t2.b = ?]),
    37. access([t2.b], [t2.c]), partitions(p0)