Firebird 在 where 和 order by 子句上的性能

Rey*_*ldi 3 sql firebird

我有一个查询,基本上可以找到特定日期范围内某些商品的最后成本。

select first 1 lastcost from stock 
where itemid = :itemid and date > :startdate and date < :enddate 
order by date desc
Run Code Online (Sandbox Code Playgroud)

此查询需要几秒钟才能完成数百万条记录,因为“>”不使用索引。如果我按年/月拆分查询并迭代直到达到开始日期(假设每月有 100 万条记录),会更快吗?

while (endate > startdate) do
begin
  var_year = extract(year from :endate);
  var_month = extract(month from :endate);
  select first 1 lastcost from stock 
  where itemid = :itemid and year=:var_year and month=:var_month
  order by date desc
  enddate = dateadd (-1 month to enddate);
end
Run Code Online (Sandbox Code Playgroud)

这几天我无法访问 Firebird,所以我自己无法尝试。

jac*_*ate 5

如果适用于 >、<、>=、<= 以及运算符之间的索引,Firebird 将使用索引。

我在用这张表发布之前做了一个测试:

SQL> show table stock2;
ITEMID                          INTEGER Not Null
STOCKDATE                       TIMESTAMP Not Null
LASTCOST                        DOUBLE PRECISION Nullable
Run Code Online (Sandbox Code Playgroud)

用一些数据填充它(不是每月数百万,但足以测试性能)

SQL> select extract(year from stockdate),
CON>        extract(month from stockdate), count(*)
CON>   from stock2
CON>  group by 1, 2
CON>  order by 1, 2;

EXTRACT EXTRACT        COUNT
======= ======= ============
   2012       1       706473
   2012       2       628924
   2012       3       670038
   2012       4       649411
   2012       5       671512
   2012       6       648878
   2012       7       671182
   2012       8       671212
   2012       9       649312
   2012      10       671881
   2012      11       648815
   2012      12       671579
Run Code Online (Sandbox Code Playgroud)

我运行了您的查询,首先没有任何索引(需要几秒钟),然后仅对 itemid 列建立索引,证明了更好的计划和更好的性能,最后使用 itemid 和日期的索引,其中性能要好得多。显示计划允许您看到引擎默认使用索引。

SQL> set plan on;
SQL>
SQL> select first 1 lastcost
CON>   from stock2
CON>  where itemid = 127
CON>    and stockdate > '2012-01-15'
CON>    and stockdate < '2012-03-27'
CON> order by stockdate desc;

PLAN SORT ((STOCK2 INDEX (IDX_STOCK2IDDATE)))

               LASTCOST
=======================
      149.7170031070709

SQL>
Run Code Online (Sandbox Code Playgroud)

我使用的索引定义是:

create index idx_stock2id on stock2 (itemid);
create index idx_stock2iddate on stock2 (itemid, stockdate);
Run Code Online (Sandbox Code Playgroud)