ORACLE:WHERE 子句中的 CASE 花费更多时间获取结果

ORACLE: CASE in WHERE clause taking more time for result

员工 Table 有 10 万条数据。

Select emp.* 
from Employee emp 
  inner join Department dept 
     on dept.Dept_no = (case when emp.Dept_NO= 11 then (select Id from CONSTANT where costant_name = 'ABC' )
                             else emp.Dept_NO end );

此查询 运行 花费了太多时间。如何使此查询 运行 快?

为了避免 selectcase 内,cross joinconstant 可能会有所帮助。不过,我猜它(constant table)很小,而且 returns 这种情况只有一行,所以无论如何都足够快了。

SELECT e.*
  FROM employee e
       CROSS JOIN constant c
       JOIN department d
          ON d.dept_no =
                CASE WHEN e.dept_no = 11 THEN c.id ELSE e.dept_no END
 WHERE c.constant_name = 'ABC';

同时,检查连接操作中涉及的列(dept_no)是否被索引。

解释计划可能会揭示一些有用的信息。

我认为你应该避免在 join 子句中使用 select 语句。

您可以使用 left join 如下:

Select emp.* 
  from Employee emp 
Left join CONSTANT const on ( costant_name = 'ABC' ) 
inner join Department dept on dept.Dept_no = case when emp.Dept_NO <> 11 
           then emp.Dept_NO
           Else const.Id
           end ;

我使用了left joinconstant table如果没有满足costant_name = 'ABC'的记录那么也应该查询return其他记录匹配 employee table.

干杯!!