欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Oracle中的半联结和反联结详解

程序员文章站 2023-11-17 19:59:22
当两张表进行联结的时候,如果表1中的数据行是否出现在结果集中需要根据表2中出现或不出现至少一个相匹配的数据行来判断,这种情况就会发生半联结;而反联结便是半联结的补集,它们会...

当两张表进行联结的时候,如果表1中的数据行是否出现在结果集中需要根据表2中出现或不出现至少一个相匹配的数据行来判断,这种情况就会发生半联结;而反联结便是半联结的补集,它们会作为数据库中常见的联结方法如nested loops,merge sort join,hash join的选项出现。

实际上半联结和反联结本身也可以被认同是两种联结方法;在cbo优化模式下,优化器能够根据实际情况灵活的转换执行语句从而实现半联结和反联结方法,毕竟没有什么sql语法可以显式的调用半联结和反联结,它们只是sql语句满足某些条件时优化器可以选择的选项而已,不过仍然有必要深入这两种选项在特定情况下带来的性能优势。

半联结

半联结通常都发生在使用含有in和exists的相关子查询的时候,=any的用法与in相同,所以也会出现发生半联结的情况;不过也是有例外的,在11gr2版本中,优化器不会为任何包含在or分支中的子查询选择半联结,这也是现在官档中唯一明确标识的限制条件,来看几种发生场景:

复制代码 代码如下:

-- 使用in关键字的相关子查询 => 发生nested loops半联结
sql> select department_name
  2  from hr.departments dept
  3  where department_id in (select department_id from hr.employees emp);

11 rows selected.

execution plan
----------------------------------------------------------
plan hash value: 2605691773

----------------------------------------------------------------------------------------
| id  | operation          | name              | rows  | bytes | cost (%cpu)| time     |
----------------------------------------------------------------------------------------
|   0 | select statement   |                   |    10 |   190 |     3   (0)| 00:00:01 |
|   1 |  nested loops semi |                   |    10 |   190 |     3   (0)| 00:00:01 |
|   2 |   table access full| departments       |    27 |   432 |     3   (0)| 00:00:01 |
|*  3 |   index range scan | emp_department_ix |    41 |   123 |     0   (0)| 00:00:01 |
----------------------------------------------------------------------------------------

predicate information (identified by operation id):
---------------------------------------------------

   3 - access("department_id"="department_id")

statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
         11  consistent gets
          0  physical reads
          0  redo size
        742  bytes sent via sql*net to client
        524  bytes received via sql*net from client
          2  sql*net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
         11  rows processed

-- 使用exists关键字的相关子查询 => 发生nested loops半联结
sql> select department_name
  2  from hr.departments dept where exists
  3  (select null from hr.employees emp where emp.department_id = dept.department_id);

11 rows selected.

execution plan
----------------------------------------------------------
plan hash value: 2605691773

----------------------------------------------------------------------------------------
| id  | operation          | name              | rows  | bytes | cost (%cpu)| time     |
----------------------------------------------------------------------------------------
|   0 | select statement   |                   |    10 |   190 |     3   (0)| 00:00:01 |
|   1 |  nested loops semi |                   |    10 |   190 |     3   (0)| 00:00:01 |
|   2 |   table access full| departments       |    27 |   432 |     3   (0)| 00:00:01 |
|*  3 |   index range scan | emp_department_ix |    41 |   123 |     0   (0)| 00:00:01 |
----------------------------------------------------------------------------------------

predicate information (identified by operation id):
---------------------------------------------------

   3 - access("emp"."department_id"="dept"."department_id")

statistics
----------------------------------------------------------
          1  recursive calls
          0  db block gets
         11  consistent gets
          0  physical reads
          0  redo size
        742  bytes sent via sql*net to client
        524  bytes received via sql*net from client
          2  sql*net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
         11  rows processed

-- 谓语中使用了or分支中的exists子查询 => 禁用半联结
sql> select department_name
  2  from hr.departments dept
  3  where 1=2 or exists
  4  (select null from hr.employees emp where emp.department_id = dept.department_id);

11 rows selected.

execution plan
----------------------------------------------------------
plan hash value: 440241596

----------------------------------------------------------------------------------------
| id  | operation          | name              | rows  | bytes | cost (%cpu)| time     |
----------------------------------------------------------------------------------------
|   0 | select statement   |                   |    27 |   432 |     4   (0)| 00:00:01 |
|*  1 |  filter            |                   |       |       |            |          |
|   2 |   table access full| departments       |    27 |   432 |     3   (0)| 00:00:01 |
|*  3 |   index range scan | emp_department_ix |     2 |     6 |     1   (0)| 00:00:01 |
----------------------------------------------------------------------------------------

predicate information (identified by operation id):
---------------------------------------------------

   1 - filter( exists (select 0 from "hr"."employees" "emp" where
              "emp"."department_id"=:b1))
   3 - access("emp"."department_id"=:b1)

statistics
----------------------------------------------------------
          1  recursive calls
          0  db block gets
         35  consistent gets
          0  physical reads
          0  redo size
        742  bytes sent via sql*net to client
        524  bytes received via sql*net from client
          2  sql*net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
         11  rows processed

从结果集来看,我们很容易联想到内联结,那为什么半联结通常来说会获得更高的性能呢?这实际也是半联结优化的关键,拿nested loops来举例,在nested loops联结中,驱动表被读取后需要逐个的进入内层循环来进行匹配工作,并且只有当外层循环的数据行与内层循环中的每一行数据匹配运算完成后才会结束一个结果集的获取;而相对而言,半联结的区别在于数据集1中的每一条记录只返回一次,而不管数据集2中有几条匹配的记录,因此,半联结会在找到子查询中匹配到的第一条数据后立即结束处理从而提高性能。

对于某些需要利用半联结来提高性能的场景,可以通过手动的方式控制半联结的执行计划,使用semijoin和no_semijoin提示分别可以指定优化器使用和禁用半联结。

复制代码 代码如下:

-- 使用no_semijoin提示禁用半联结
sql> select department_name
  2  from hr.departments dept
  3  where department_id in (select /*+ no_semijoin */department_id from hr.employees emp);

11 rows selected.

execution plan
----------------------------------------------------------
plan hash value: 3372191744

------------------------------------------------------------------------------------------
| id  | operation            | name              | rows  | bytes | cost (%cpu)| time     |
------------------------------------------------------------------------------------------
|   0 | select statement     |                   |   106 |  1802 |     4  (25)| 00:00:01 |
|   1 |  view                | vm_nwvw_2         |   106 |  1802 |     4  (25)| 00:00:01 |
|   2 |   hash unique        |                   |   106 |  2544 |     4  (25)| 00:00:01 |
|   3 |    nested loops      |                   |   106 |  2544 |     3   (0)| 00:00:01 |
|   4 |     table access full| departments       |    27 |   567 |     3   (0)| 00:00:01 |
|*  5 |     index range scan | emp_department_ix |     4 |    12 |     0   (0)| 00:00:01 |
------------------------------------------------------------------------------------------

predicate information (identified by operation id):
---------------------------------------------------

   5 - access("department_id"="department_id")

statistics
----------------------------------------------------------
        506  recursive calls
          0  db block gets
        188  consistent gets
          7  physical reads
          0  redo size
        742  bytes sent via sql*net to client
        524  bytes received via sql*net from client
          2  sql*net roundtrips to/from client
         10  sorts (memory)
          0  sorts (disk)
         11  rows processed

除此之外,我们还可以使用_always_semi_join隐藏参数选择半联结的联结类型,有关_always_semi_join参数的可选值:

复制代码 代码如下:

sql> select
  2           parno_kspvld_values     pvalid_par#,
  3           name_kspvld_values      pvalid_name,
  4           value_kspvld_values     pvalid_value,
  5           decode(isdefault_kspvld_values, 'false', '', 'default' ) pvalid_default
  6   from
  7           x$kspvld_values
  8   where
  9           lower(name_kspvld_values) like '%'||lower(nvl('&pname',name_kspvld_values))||'%'
 10   order by
 11           pvalid_par#,
 12           pvalid_default,
 13           pvalid_value
 14   /

  par# parameter                                          value                          default
------ -------------------------------------------------- ------------------------------ -------
  1705 _always_semi_join                                  choose
       _always_semi_join                                  hash
       _always_semi_join                                  merge
       _always_semi_join                                  nested_loops
       _always_semi_join                                  off

该参数的默认值为choose,表示选用半联结的类型由优化器来决定,下面来使用_always_semi_join参数将上面的nested loops半联结改变为hash join半联结:

复制代码 代码如下:

-- 默认发生nested loops semi
sql> select department_name
  2  from hr.departments dept
  3  where department_id in (select department_id from hr.employees emp);

11 rows selected.

execution plan
----------------------------------------------------------
plan hash value: 2605691773

----------------------------------------------------------------------------------------
| id  | operation          | name              | rows  | bytes | cost (%cpu)| time     |
----------------------------------------------------------------------------------------
|   0 | select statement   |                   |    10 |   190 |     3   (0)| 00:00:01 |
|   1 |  nested loops semi |                   |    10 |   190 |     3   (0)| 00:00:01 |
|   2 |   table access full| departments       |    27 |   432 |     3   (0)| 00:00:01 |
|*  3 |   index range scan | emp_department_ix |    41 |   123 |     0   (0)| 00:00:01 |
----------------------------------------------------------------------------------------

predicate information (identified by operation id):
---------------------------------------------------

   3 - access("department_id"="department_id")

statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
         11  consistent gets
          0  physical reads
          0  redo size
        742  bytes sent via sql*net to client
        524  bytes received via sql*net from client
          2  sql*net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
         11  rows processed

-- session级别修改参数
sql> alter session set "_always_semi_join"=merge;

session altered.

-- 发生merge join semi
sql> select department_name
  2  from hr.departments dept
  3  where department_id in (select department_id from hr.employees emp);

11 rows selected.

execution plan
----------------------------------------------------------
plan hash value: 954076352

--------------------------------------------------------------------------------------------------
| id  | operation                    | name              | rows  | bytes | cost (%cpu)| time     |
--------------------------------------------------------------------------------------------------
|   0 | select statement             |                   |    10 |   190 |     4  (25)| 00:00:01 |
|   1 |  merge join semi             |                   |    10 |   190 |     4  (25)| 00:00:01 |
|   2 |   table access by index rowid| departments       |    27 |   432 |     2   (0)| 00:00:01 |
|   3 |    index full scan           | dept_id_pk        |    27 |       |     1   (0)| 00:00:01 |
|*  4 |   sort unique                |                   |   107 |   321 |     2  (50)| 00:00:01 |
|   5 |    index full scan           | emp_department_ix |   107 |   321 |     1   (0)| 00:00:01 |
--------------------------------------------------------------------------------------------------

predicate information (identified by operation id):
---------------------------------------------------

   4 - access("department_id"="department_id")
       filter("department_id"="department_id")

statistics
----------------------------------------------------------
          1  recursive calls
          0  db block gets
          5  consistent gets
          1  physical reads
          0  redo size
        742  bytes sent via sql*net to client
        523  bytes received via sql*net from client
          2  sql*net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
         11  rows processed
-- 从trace来看优化器的选择还是非常可靠的。。

反联结

从本质上来说,反联结和半联结很多相似的因素,反联结的发生通常是在使用含有not in,not exists的相关子查询的时候,同样,如果子查询谓语or分支中,反联结也会被禁用,它和半联结主要的不同点还是在返回数据的匹配方式上,它是会返回在子查询中没有匹配到的数据行,不过其优化的原理是一致的,通过在子查询中找到第一条匹配记录而立即停止处理来提高效率,一下是发生的集中场景:

复制代码 代码如下:

sql> set autotrace traceonly
-- not in 触发反联结
sql> select department_name
  2  from hr.departments
  3  where department_id not in
  4  (select department_id from hr.employees where department_id is not null);

16 rows selected.

execution plan
----------------------------------------------------------
plan hash value: 3082375452

----------------------------------------------------------------------------------------
| id  | operation          | name              | rows  | bytes | cost (%cpu)| time     |
----------------------------------------------------------------------------------------
|   0 | select statement   |                   |    17 |   323 |     3   (0)| 00:00:01 |
|   1 |  nested loops anti |                   |    17 |   323 |     3   (0)| 00:00:01 |
|   2 |   table access full| departments       |    27 |   432 |     3   (0)| 00:00:01 |
|*  3 |   index range scan | emp_department_ix |    41 |   123 |     0   (0)| 00:00:01 |
----------------------------------------------------------------------------------------

predicate information (identified by operation id):
---------------------------------------------------

   3 - access("department_id"="department_id")
       filter("department_id" is not null)

statistics
----------------------------------------------------------
          1  recursive calls
          0  db block gets
         12  consistent gets
          6  physical reads
          0  redo size
        985  bytes sent via sql*net to client
        535  bytes received via sql*net from client
          3  sql*net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
         16  rows processed

-- exists触发反联结
sql> select department_name
  2  from hr.departments dept
  3  where not exists
  4  (select null from hr.employees emp where emp.department_id = dept.department_id);

16 rows selected.

execution plan
----------------------------------------------------------
plan hash value: 3082375452

----------------------------------------------------------------------------------------
| id  | operation          | name              | rows  | bytes | cost (%cpu)| time     |
----------------------------------------------------------------------------------------
|   0 | select statement   |                   |    17 |   323 |     3   (0)| 00:00:01 |
|   1 |  nested loops anti |                   |    17 |   323 |     3   (0)| 00:00:01 |
|   2 |   table access full| departments       |    27 |   432 |     3   (0)| 00:00:01 |
|*  3 |   index range scan | emp_department_ix |    41 |   123 |     0   (0)| 00:00:01 |
----------------------------------------------------------------------------------------

predicate information (identified by operation id):
---------------------------------------------------

   3 - access("emp"."department_id"="dept"."department_id")

statistics
----------------------------------------------------------
          3  recursive calls
          0  db block gets
         13  consistent gets
          0  physical reads
          0  redo size
        985  bytes sent via sql*net to client
        535  bytes received via sql*net from client
          3  sql*net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
         16  rows processed


从上面的例子可以看出minus和outer join操作都可以巧妙的实现同样的结果,不过从执行计划来看,minus操作显然没有反联结操作优化,而使用outer join虽然发生了反联结优化,但是由于使用了带空值的虚拟记录来匹配数据行,不便于理解,因此实际还是不建议使用的。

如果想要手动控制反联结的执行计划,这里也有一些hint和参数可以使用,常用的hint有:

1.antijoin-进行反联结,优化器决定联结类型
2.use_anti-老版本的提示,和antijoin功能一致
3.[nl_aj] | [hash_aj] | [merge_aj]-指定发生反联结的类型(10g开始被弃用,不过仍然可以生效)

在参数控制方面,也有个和_always_semi_join非常相同的_always_anti_join参数,用法完全一致;还有参数_optimizer_null_aware_antijoin,_optimizer_outer_to_anti_enable用于控制对含空值和外联结的反联结转换。

复制代码 代码如下:

-- 使用hint显式指定反联结类型
sql> select department_name
  2  from hr.departments dept
  3  where not exists (select /*+ hash_aj */ null from hr.employees emp
  4  where emp.department_id = dept.department_id);

16 rows selected.

execution plan
----------------------------------------------------------
plan hash value: 3587451639

----------------------------------------------------------------------------------------
| id  | operation          | name              | rows  | bytes | cost (%cpu)| time     |
----------------------------------------------------------------------------------------
|   0 | select statement   |                   |    17 |   323 |     5  (20)| 00:00:01 |
|*  1 |  hash join anti    |                   |    17 |   323 |     5  (20)| 00:00:01 |
|   2 |   table access full| departments       |    27 |   432 |     3   (0)| 00:00:01 |
|   3 |   index full scan  | emp_department_ix |   107 |   321 |     1   (0)| 00:00:01 |
----------------------------------------------------------------------------------------

predicate information (identified by operation id):
---------------------------------------------------

   1 - access("emp"."department_id"="dept"."department_id")

statistics
----------------------------------------------------------
        566  recursive calls
          0  db block gets
        193  consistent gets
          0  physical reads
          0  redo size
        985  bytes sent via sql*net to client
        535  bytes received via sql*net from client
          3  sql*net roundtrips to/from client
         12  sorts (memory)
          0  sorts (disk)
         16  rows processed

-- 使用_optimizer_null_antijoin参数关闭反联结中的空值考虑选项-即返回空值的情况不使用反联结
sql> alter session set "_optimizer_null_aware_antijoin"=false;

session altered.

sql> select department_name
  2  from hr.departments
  3  where department_id not in (select department_id from hr.employees);

no rows selected

execution plan
----------------------------------------------------------
plan hash value: 3416340233

----------------------------------------------------------------------------------
| id  | operation          | name        | rows  | bytes | cost (%cpu)| time     |
----------------------------------------------------------------------------------
|   0 | select statement   |             |    26 |   416 |    30   (0)| 00:00:01 |
|*  1 |  filter            |             |       |       |            |          |
|   2 |   table access full| departments |    27 |   432 |     3   (0)| 00:00:01 |
|*  3 |   table access full| employees   |     2 |     6 |     2   (0)| 00:00:01 |
----------------------------------------------------------------------------------

predicate information (identified by operation id):
---------------------------------------------------

   1 - filter( not exists (select 0 from "hr"."employees" "employees"
              where lnnvl("department_id"<>:b1)))
   3 - filter(lnnvl("department_id"<>:b1))

statistics
----------------------------------------------------------
          1  recursive calls
          0  db block gets
        172  consistent gets
          0  physical reads
          0  redo size
        343  bytes sent via sql*net to client
        513  bytes received via sql*net from client
          1  sql*net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          0  rows processed