SQL查询需要15到20秒

时间:2018-07-11 11:38:25

标签: sql oracle performance refactoring sql-tuning

The Query Explain Plan Link

以下查询占用15至20秒的时间,这是意外的。请协助重构此查询

SELECT upin.bipuserid userid,
       upin.orgn_entity_id entityId,
       COUNT(upin.ORGN_ENTITY_ID)
           over (partition BY upin.bipuserid) as numentities,
       COUNT(DISTINCT(SUBSTR(upin.ORGN_ENTITY_ID,6,2)))
           over (partition BY upin.bipuserid) as numentitytypes
FROM userpermission upin;

表中有1614246个记录。在两列上都创建了索引。

下面是表格结构

Column Name        Data Type    

BIPUSERID         VARCHAR2 (20 Char)            
ROLECODE          VARCHAR2 (25 Char)            
ORGN_ENTITY_ID    VARCHAR2 (10 Char)            
ACT_CD            VARCHAR2 (1 Char)         

2 个答案:

答案 0 :(得分:1)

此查询需要多长时间?

select count(orgn_entity_id) as numentities ,
       count(distinct substr(upin.ORGN_ENTITY_ID, 6, 2) ) as numentitytypes
from userpermission upin
group by upin.bipuserid;

如果速度显着提高,那么您可以join重新输入这些结果。这也许可以利用userpermission(bipuserid, substr(upin.ORGN_ENTITY_ID, 6, 2), orgn_entity_id)上的索引。

答案 1 :(得分:0)

我相信@GordonLinoff的建议是,您应该使用他的查询作为类似以下内容的基础:

WITH cteCounts AS (SELECT BIPUSERID,
                          COUNT(ORGN_ENTITY_ID) AS NUMENTITIES ,
                          COUNT(DISTINCT SUBSTR(ORGN_ENTITY_ID, 6, 2) ) AS NUMENTITYTYPES
                     FROM USERPERMISSION
                     GROUP BY BIPUSERID)
SELECT c.BIPUSERID,
       up.ORGN_ENTITY_ID AS ENTITYID,
       c.NUMENTITIES,
       c.NUMENTITYTYPES
  FROM cteCounts c
  INNER JOIN USERPERMISSION up
    ON up.BIPUSERID = c.BIPUSERID

并添加如下索引:

CREATE INDEX USERPERMISSION_XXX(BIPUSERID, SUBSTR(ORGN_ENTITY_ID, 6, 2), ORGN_ENTITY_ID);

创建索引,然后运行上面的查询,希望它对您来说会更快一些。

好运。