首页 > 解决方案 > Oracle 子查询分解不适用于函数调用

问题描述

我正在使用 Oracle 11g。我有一个需要 6 秒才能执行的查询

 select *
   from tab1
  where exists (select 1
           from tab2
          where tab2.col1 = tab1.col1
            and tab2.col2 = pkg1.fn1('STRING'));

突出显示的函数返回一个常量值 = 1。(该函数有 1 个查询,当独立执行时,在 < 1 秒内返回结果。

如果我硬编码 1 而不是调用函数,查询会在 < 1 秒内返回相同的结果。

我不想在函数等中使用 RESULT_CACHE。我想重写查询以使其更快。

方法一:无时差 将函数内的查询带出来,作为子查询使用

and tab2.col2 = pkg1.fn1('STRING')

变成

and tab2.col2 = (query within the function is written here)

方法 2:增加时间 将函数内的查询带出并用作与 exists 子句内的整体查询的内连接。

方法 3:没有变化

with factoring as (select pkg1.fn1('STRING') as return_val from dual)
 select *
   from tab1
  where exists (select 1
           from tab2, factoring
          where tab2.col1 = tab1.col1
            and tab2.col2 = factoring.return_val);

方法 4:没有变化

with factoring as (select pkg1.fn1('STRING') as return_val from dual)
 select *
   from tab1, factoring
  where exists (select 1
           from tab2
          where tab2.col1 = tab1.col1
            and tab2.col2 = factoring.return_val);

我想了解以下
1. 为什么方法 3 和 4 不起作用
2. 如何优化此查询?

标签: performanceoracle11gquery-tuning

解决方案


推荐阅读