如何优化具有多个OR条件的pl sql if语句

时间:2019-04-09 04:33:08

标签: sql oracle plsql

我是pl sql的新手,您能告诉我如何优化以下if语句吗?

jquery.js:9175 POST http://localhost/site/fetch.php 404 (Not Found)

就像在sql中一样,我们可以使用

IF (inSeries=‘90’) OR (inSeries=‘91’) OR (inSeries=‘92’) OR (inSeries=‘93’) OR (inSeries=‘94’) THEN

3 个答案:

答案 0 :(得分:3)

在PLSQL中,“ IN”条件也可以用作IF条件

declare
inSeries varchar2(2) := '90';
begin
if inseries in ('90','91','92','93','94')
then
dbms_output.put_line(inseries ||':this is within series');
else
dbms_output.put_line(inseries ||':this is out of series');
end if;
end;

-- output
90:this is within series
80:this is out of series

但是还有另一种方式取决于业务逻辑,正如我从您的问题中看到的那样,它以系列递增,您可以直接使用大于和小于组合...

答案 1 :(得分:1)

Optimizer很可能会重写查询,因此您的IN仍将变成OR。比较查询中的第3行和最后一行:

SQL> select job
  2  from emp
  3  where deptno in (10, 20, 30, 40);

JOB
---------
CLERK
SALESMAN
<snip>

14 rows selected.


Execution Plan
----------------------------------------------------------
Plan hash value: 3956160932

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |    14 |   154 |     3   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| EMP  |    14 |   154 |     3   (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("DEPTNO"=10 OR "DEPTNO"=20 OR "DEPTNO"=30 OR "DEPTNO"=40)

SQL>

答案 2 :(得分:1)

您可以将SQL查询本身与“ EXISTS”关键字一起使用。

IF EXISTS (SELECT * FROM <table_name> WHERE inSeries IN (‘90’,’91’,’92’,’93’,’94’))