加速oracle SQL查询
Posted
技术标签:
【中文标题】加速oracle SQL查询【英文标题】:Speed up oracle SQL query 【发布时间】:2019-02-06 09:55:23 【问题描述】:我有一个查询,我正在尝试优化一个运行需要 6 分钟的查询(DS1 有 200k 行,DS2 也有 200k 行)。我想知道甲骨文大师是否可以看到任何优化? 我绝不是专家,更像是一个业余爱好者......问题看起来像分组部分花费的时间最长......
WITH DS1 AS
(SELECT
/*+ PARALLEL */
*
FROM PD1
WHERE TYPE = 'TSY'
AND SOURCE = 'A'
),
DS2 AS
(SELECT
/*+ PARALLEL */
*
FROM PD1
WHERE TYPE = 'LGL'
AND SOURCE = 'B'
),
Q AS
(SELECT DS1.ID AS DS1_ID,
DS1.CODE AS DS1_CODE,
DS2.CODE AS DS2_CODE,
DS2.ID AS DS2_ID,
DS1.TYPE AS TYPE1,
DS2.TYPE AS TYPE2,
DS1.SOURCE AS SS1,
DS2.SOURCE AS SS2,
DS1.ATTRIBUTE,
DS1.ATTRIBUTE_VAL,
DS1.ATT_AND_VAL
FROM DS1
JOIN DS2
ON DS1.ATT_AND_VAL = DS2.ATT_AND_VAL
) ,
GROUPINGS AS
(SELECT
/*+no_merge */
DS1_ID AS BASE_ID ,
DS1_CODE AS BASE_CODE,
DS2_CODE AS TARGET_CODE,
COUNT(DISTINCT(DS2_ID)) AS COUNT_OF_TARGET_ID
FROM Q
GROUP BY DS1_ID,
DS1_CODE,
DS2_CODE
)
SELECT *
FROM GROUPINGS
ORDER BY BASE_ID,
BASE_CODE,
TARGET_CODE;
【问题讨论】:
首先要做的是检查解释计划。请获取解释计划输出(作为文本,而不是图像)并将其包含在您的问题中。 另外,PD1 表的主键/唯一键是什么? 【参考方案1】:我很想通过删除所有公用表表达式和提示来简化现有查询。像这样:
SELECT
DS1_ID AS BASE_ID
, DS1_CODE AS BASE_CODE
, DS2_CODE AS TARGET_CODE
, COUNT( DISTINCT (DS2_ID) ) AS COUNT_OF_TARGET_ID
FROM (
SELECT
DS1.ID AS DS1_ID
, DS1.CODE AS DS1_CODE
, DS2.CODE AS DS2_CODE
, DS2.ID AS DS2_ID
FROM PD1 DS1
JOIN PD1 DS2 ON DS1.ATT_AND_VAL = DS2.ATT_AND_VAL
AND DS2.TYPE = 'LGL'
AND DS2.SOURCE = 'B'
WHERE DS1.TYPE = 'TSY'
AND DS1.SOURCE = 'A'
) Q
GROUP BY
DS1_ID
, DS1_CODE
, DS2_CODE
ORDER BY
BASE_ID
, BASE_CODE
, TARGET_CODE
;
如果这需要几分钟才能运行,那么我建议您需要添加索引。首先要做的是制定解释计划,以确定是否使用任何索引来缩小后续步骤的范围。
【讨论】:
以上是关于加速oracle SQL查询的主要内容,如果未能解决你的问题,请参考以下文章