[Oracle]优化查询包含最大子查询

时间:2016-01-05 07:44:13

标签: oracle oracle11g max query-optimization

我想知道是否有办法根据该请求优化视图:

SELECT product ,
  price ,
  quantity_in_stock ,
  location
FROM mytableA x
WHERE x.price =
  (SELECT MAX( z.price )
  FROM mytableA z
  WHERE (z.quantity_in_stock > 0)
  AND z.product          = x.product
  ); 

谢谢。

1 个答案:

答案 0 :(得分:1)

使用分析函数(单表扫描)而不是相关的子查询(两个表扫描):

SELECT product,
       price,
       quantity_in_stock,
       location
FROM   (
  SELECT product,
         price,
         quantity_in_stock,
         location,
         MAX( CASE WHEN quantity_in_stock > 0 THEN price END ) OVER ( PARTITION BY product ) AS max_price_in_stock
  FROM   MyTable
)
WHERE price = max_price_in_stock;