SQL优化案例——in和exist的优化

涉及知识:in 和 exist的原理
问题现象:
在应收应付的单据相关业务中,出现了明显的SQL效率问题。SQL执行耗时三分钟以上。
由于最终查询数据量较小,故认为可以优化至3秒以内。
问题SQL如下
SELECT DISTINCT ar_recbill.pk_recbill,
ar_recbill.billdate,
ar_recbill.billno
FROM ar_recbill ar_recbill
WHERE (ar_recbill.pk_org = '00014910000000002Z8G' AND
(ar_recbill.billdate >= '2015-12-14 00:00:00' and
ar_recbill.billdate <= '2015-12-14 23:59:59'))
AND ar_recbill.billstatus <> 9
AND ar_recbill.isinit = 'N'
AND ar_recbill.pk_group = '00013910000000000N4S'
AND (ar_recbill.pk_recbill NOT IN
(SELECT fr.src_relationid
FROM fip_relation fr
where fr.des_org in (select pk_accountingbook
from org_accountingbook
where accounttype = 1)))
AND ar_recbill.dr = 0
ORDER BY ar_recbill.billdate, ar_recbill.billno

问题分析:
从语句中我们可以看到,并没有复杂的连接操作,所以效率问题应该是在where的选择条件中。而这里比较可疑的条件就是 not in语句的存在。通过执行计划,我们可以确信这一点。
Plan hash value: 920333179


| Id | Operation | Name | Starts | E-Rows | A-Rows | A-Time | Buffers | Reads | OMem | 1Mem | Used-Mem |

| 0 | SELECT STATEMENT | | 1 | | 11 |00:03:34.92 | 13M| 12M| | | |
| 1 | SORT ORDER BY | | 1 | 1 | 11 |00:03:34.92 | 13M| 12M| 2048 | 2048 | 2048 (0)|
|* 2 | FILTER | | 1 | | 11 |00:03:34.92 | 13M| 12M| | | |
|* 3 | TABLE ACCESS BY INDEX ROWID | AR_RECBILL | 1 | 1 | 11 |00:00:00.01 | 11 | 0 | | | |
|* 4 | INDEX RANGE SCAN | AR_RECBILL_BILLDATE | 1 | 1 | 11 |00:00:00.01 | 3 | 0 | | | |
| 5 | NESTED LOOPS | | 11 | 1 | 0 |00:03:34.92 | 13M| 12M| | | |
| 6 | NESTED LOOPS | | 11 | 1 | 0 |00:03:34.92 | 13M| 12M| | | |
|* 7 | TABLE ACCESS FULL | FIP_RELATION | 11 | 1 | 0 |00:03:34.92 | 13M| 12M| | | |
|* 8 | INDEX UNIQUE SCAN | PK__ACCOUNTINGBOOK | 0 | 1 | 0 |00:00:00.01 | 0 | 0 | | | |
|* 9 | TABLE ACCESS BY INDEX ROWID| ORG_ACCOUNTINGBOOK | 0 | 1 | 0 |00:00:00.01 | 0 | 0 | | | |


Predicate Information (identified by operation id):

2 - filter( IS NULL)
3 - filter(("AR_RECBILL"."ISINIT"='N' AND "AR_RECBILL"."DR"=0 AND "AR_RECBILL"."BILLSTATUS"<>9 AND
"AR_RECBILL"."PK_GROUP"='00013910000000000N4S'))
4 - access("AR_RECBILL"."PK_ORG"='00014910000000002Z8G' AND "AR_RECBILL"."BILLDATE">='2015-12-14 00:00:00' AND
"AR_RECBILL"."BILLDATE"<='2015-12-14 23:59:59')
7 - filter(LNNVL("FR"."SRC_RELATIONID"<>:B1))
8 - access("FR"."DES_ORG"="PK_ACCOUNTINGBOOK")
9 - filter("ACCOUNTTYPE"=1)

我们可以发现,最耗时的语句为7,走了全表扫描。而这个全表扫描,走了filter。看到filter我们得知,SQL没有走索引,同时还进行了函数的转换。LNNVL("FR"."SRC_RELATIONID"<>:B1。源SQL语句中是查询pk_recbill NOT IN SELECT fr.src_relationid。这里发生了隐式转化。

问题解决:

你可能感兴趣的:(SQL优化案例——in和exist的优化)