【问题标题】:How to optimize where clause query that contains to_char如何优化包含 to_char 的 where 子句查询
【发布时间】:2020-08-10 17:25:01
【问题描述】:

当我使用解释计划时,我需要优化 where 子句查询以降低成本。

以下是原文

create index idx on orders(o_orderdate)

select *
from orders
where (to_char(o_orderdate, 'dd-mon-yy') = '23-MAR-97' and o_totalprice > 2) or (not o_custkey > 3 and to_char(o_orderdate, 'dd-mon-yyyy') = '23-MAR-1997');

这是我从原始查询中得到的解释计划

但是当我尝试使用这个查询来优化它时

select * 
from orders
where o_totalprice > 2
and o_custkey < 3
and o_orderdate >= to_date('23MAR97', 'dd-mon-yy') 
and o_orderdate <= to_date('24MAR1997', 'dd-mon-yyyy');

它返回没有选择的行

如何优化原来的 where 查询仍然返回 4500 行?

【问题讨论】:

  • 任何时候你把一个函数放在比较的左侧(其中 to_char(my_date)... 你消除了在该列上使用索引的可能性(除非你有一个基于函数的索引). 另外,比较日期时,需要比较 DATE,而不是 to_char 字符表示。另外,请务必始终使用 4 位数年份,不要重新创建 Y2k 错误。

标签: mysql oracle


【解决方案1】:

您没有正确考虑OR。应该是:

select *
from orders
where o_orderdate between to_date('23-MAR-1997','DD-MON-YYYY') 
         and to_date('24-MAR-1997','DD-MON-YYYY') - INTERVAL '1' SECOND
and ( o_totalprice > 2
   or not o_custkey > 3 )
;

【讨论】:

  • 嗨,它仍然没有返回任何选择的行
  • 对不起——我的查询中有错字。我有23-MAY 而不是23-MAR。请再试一次。
  • 谢谢!现在成本下降到 558 而不是原来的 2703
猜你喜欢
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多