如何针对指定代码优化以下查询

时间:2015-01-08 07:07:43

标签: sql performance query-optimization oracle-sqldeveloper

SELECT a.id, a.stock_num, a.stock_rfrnc_num,
       a.date, a.center, a.owner,
       a.owner_id, a.product_typ, a.transaction_dt,
       a.location, a.status
  FROM a
 WHERE a.status = 'Ready'
   AND a.owner_id != 'stockholder' 
    AND a.owner_id='stockseller'
      AND (a.product_typ = '03' OR a.product_typ = '04');

产品类型从1到5, owner_id有六种类型, 状态有5种类型, 这可以进一步优化吗?

4 个答案:

答案 0 :(得分:0)

您可以在运算符中使用而不是或。

AND a.product_typ in ('03','04');

下面的行不是必要的。

 AND a.owner_id != 'stockholder'

答案 1 :(得分:0)

SELECT a.id, a.stock_num, a.stock_rfrnc_num,
       a.date, a.center, a.owner,
       a.owner_id, a.product_typ, a.transaction_dt,
       a.location, a.status
  FROM a
 WHERE a.status = 'Ready'
    AND a.owner_id='stockseller'
      AND a.product_typ in ('03','04');

答案 2 :(得分:0)

创建一个B-Tree index的合并leading column status

create index index_name on table_name(status, owner_id, product_typ)

请注意索引中的前导列。如果您确定数据的唯一性,则可以创建unique索引。以上内容将创建NORMAL索引,该索引由defualt NON-UNIQUE生成。

您的谓词似乎不必要地复杂化。以下没有意义 -

 AND a.owner_id != 'stockholder' 
    AND a.owner_id='stockseller'

从谓词中删除不相等的过滤器,因为行将按AND a.owner_id != 'stockholder'过滤。

如果正在使用索引,请检查查询的explain plan

答案 3 :(得分:0)

如果您有索引Lalit Kumar建议您最好在where子句中使用UNION ALL而不是OR。如果这是此表上使用的唯一查询,则可能希望将该索引设置为聚簇索引。否则,您可能会考虑在索引中包含所有必需的列。

SELECT a.id, a.stock_num, a.stock_rfrnc_num,
       a.date, a.center, a.owner,
       a.owner_id, a.product_typ, a.transaction_dt,
       a.location, a.status
  FROM a
 WHERE a.status = 'Ready'
    AND a.owner_id = 'stockseller'
    AND a.product_typ = '03'

UNION ALL

SELECT a.id, a.stock_num, a.stock_rfrnc_num,
       a.date, a.center, a.owner,
       a.owner_id, a.product_typ, a.transaction_dt,
       a.location, a.status
  FROM a
 WHERE a.status = 'Ready'
    AND a.owner_id = 'stockseller'
    AND a.product_typ = '04';