java 针对选择的Oracle查询优化

idfiyjo8  于 2023-01-16  发布在  Java
关注(0)|答案(2)|浏览(135)

下面是我的查询,我想知道是否有任何优化可能在这个查询或没有?
仅供参考,我已经在C_NUMBER、CA_NUMBER和D_TIMESTAMP列上应用了索引。

SELECT
  NAM, RSON, URL
FROM TM_CAM
WHERE C_NUMBER = A_C_NUMBER
  AND CA_NUMBER = A_CA_NUMBER
  AND (SYSTIMESTAMP) <= D_TIMESTAMP
ORDER BY D_TIMESTAMP DESC
FETCH FIRST 1 ROWS ONLY

有一个ORDER BY,所以我认为从性能的Angular 来看它并不好。
我在下面试过了,但性能下降。

SELECT
  NAM, RSON, URL
FROM TM_CAM
WHERE D_TIMESTAMP = (
  SELECT MAX(D_TIMESTAMP )
  FROM TM_CAM
  )
  AND C_NUMBER = A_C_NUMBER
  AND CA_NUMBER = A_CA_NUMBER
  AND (SYSTIMESTAMP) <= D_TIMESTAMP

有什么意见吗?

iovurdzv

iovurdzv1#

排序会减慢速度,这是肯定的。
您的第一个查询看起来不错;涉及到多少行?你期望什么样的优化?我猜你关心的是执行时间;如果是,查询需要多长时间?检查了解释计划吗?
同时,试试

WITH
   temp
   AS
      (SELECT nam,
              rson,
              url,
              ROW_NUMBER () OVER (ORDER BY d_timestamp DESC) rn
         FROM tm_nam
        WHERE     c_number = a_c_number
              AND ca_number = a_ca_number
              AND SYSTIMESTAMP <= d_timestamp)
SELECT nam, rson, url
  FROM temp
 WHERE rn = 1;

WITH
   temp
   AS
      (  SELECT nam, rson, url
           FROM tm_nam
          WHERE     c_number = a_c_number
                AND ca_number = a_ca_number
                AND SYSTIMESTAMP <= d_timestamp
       ORDER BY d_timestamp DESC)
SELECT nam, rson, url
  FROM temp
 WHERE ROWNUM = 1;
2hh7jdfx

2hh7jdfx2#

您的第一个和第二个查询不一样,因为第二个查询相当于:

SELECT NAM, RSON, URL
FROM   TM_CAM
WHERE  C_NUMBER     =  A_C_NUMBER
AND    CA_NUMBER    =  A_CA_NUMBER
AND    SYSTIMESTAMP <= D_TIMESTAMP
ORDER BY D_TIMESTAMP DESC
FETCH FIRST ROW WITH TIES

可以使用ROWNUM重写它:

SELECT *
FROM   (
  SELECT NAM, RSON, URL
  FROM   TM_CAM
  WHERE  C_NUMBER     =  A_C_NUMBER
  AND    CA_NUMBER    =  A_CA_NUMBER
  AND    SYSTIMESTAMP <= D_TIMESTAMP
  ORDER BY D_TIMESTAMP DESC
)
WHERE  ROWNUM = 1;

但是,如果比较执行计划,您可能会发现Oracle对FETCH FIRST ROW ONLYROWNUM = 1过滤或ROW_NUMBER()分析函数过滤使用非常相似(如果不完全相同)的计划,因此您可能会选择最容易维护和使用的查询。
fiddle

相关问题