这是一个加入,我们可以优化此查询吗?

时间:2018-02-13 13:00:42

标签: sql oracle

这是一个选择查询,看起来像在表上做2选择然后在结果上做一个子查询来查找最终输出。

WITH TABLE1 AS
  (SELECT ID
   FROM SERVICE_INSTANCE TABLEA
   WHERE TABLEA.U_VC_NAME_NORM = ?)
SELECT ID,
       U_VC_SERVICE_TYPE AS SERVICE_INSTANCE_ATTR_4,
       U_VC_VLBR_PERMANENT_URL AS SERVICE_INSTANCE_ATTR_15,
       U_VC_CLOUD_ACCOUNT_ID AS SERVICE_INSTANCE_ATTR_9,
       U_VC_ENTITLEMENT_ID AS SERVICE_INSTANCE_ATTR_12,
       U_DT_REPLICATED_DATE AS SERVICE_INSTANCE_ATTR_33,
       U_VC_NAME AS SERVICE_INSTANCE_ATTR_1,
       ID AS SERVICE_INSTANCE_ATTR_20,
       U_VC_IDCS_TENANT_GUID AS SERVICE_INSTANCE_ATTR_5
FROM SERVICE_INSTANCE TABLEA
WHERE TABLEA.MAPPING_PATH = ?
  AND EXISTS
    (SELECT ID
     FROM TABLE1
     WHERE TABLEA.ID=TABLE1.ID)

我认为可以用

代替
SELECT ID,
       U_VC_SERVICE_TYPE AS SERVICE_INSTANCE_ATTR_4,
       U_VC_VLBR_PERMANENT_URL AS SERVICE_INSTANCE_ATTR_15,
       U_VC_CLOUD_ACCOUNT_ID AS SERVICE_INSTANCE_ATTR_9,
       U_VC_ENTITLEMENT_ID AS SERVICE_INSTANCE_ATTR_12,
       U_DT_REPLICATED_DATE AS SERVICE_INSTANCE_ATTR_33,
       U_VC_NAME AS SERVICE_INSTANCE_ATTR_1,
       ID AS SERVICE_INSTANCE_ATTR_20,
       U_VC_IDCS_TENANT_GUID AS SERVICE_INSTANCE_ATTR_5
FROM SERVICE_INSTANCE TABLEA
WHERE TABLEA.MAPPING_PATH = ? AND ID != NULL

我说错了吗?

首次查询计划是 Plan for First query

计划第二次查询是 Plan for second query

尝试使用5000行或<100行时,计划成本看起来完全相同。

2 个答案:

答案 0 :(得分:1)

评论时间有点长。

不,他们不一样。这个条件不在第二个查询中:

U_VC_NAME_NORM = ?

在某些情况下,他们可能会做同样的事情,但这在很大程度上取决于数据。

我怀疑第一个查询可以简化。但是,您的问题需要样本数据和期望的结果,以帮助其他人理解它。

答案 1 :(得分:1)

不 - 但它等同于;

SELECT ID,
       U_VC_SERVICE_TYPE AS SERVICE_INSTANCE_ATTR_4,
       U_VC_VLBR_PERMANENT_URL AS SERVICE_INSTANCE_ATTR_15,
       U_VC_CLOUD_ACCOUNT_ID AS SERVICE_INSTANCE_ATTR_9,
       U_VC_ENTITLEMENT_ID AS SERVICE_INSTANCE_ATTR_12,
       U_DT_REPLICATED_DATE AS SERVICE_INSTANCE_ATTR_33,
       U_VC_NAME AS SERVICE_INSTANCE_ATTR_1,
       ID AS SERVICE_INSTANCE_ATTR_20,
       U_VC_IDCS_TENANT_GUID AS SERVICE_INSTANCE_ATTR_5
FROM SERVICE_INSTANCE TABLEA
WHERE TABLEA.MAPPING_PATH = ? AND TABLEA.U_VC_NAME_NORM = ? AND TABLEA.ID IS NOT NULL

当您的CTE正在检查U_VC_NAME_NORM =?