Sql Firebird在where和order by条款上的履行
我有一个查询,基本上可以找到特定日期范围内特定项目的最后成本Sql Firebird在where和order by条款上的履行,sql,database,firebird,Sql,Database,Firebird,我有一个查询,基本上可以找到特定日期范围内特定项目的最后成本 select first 1 lastcost from stock where itemid = :itemid and date > :startdate and date < :enddate order by date desc 这几天我没有机会接触到firebird,所以我自己也没试过 提前谢谢 问候, 雷诺第不,循环迭代总是比传统的SELECT语句慢 如果可以,则“”将使用索引;查看在索引中添加'item
select first 1 lastcost from stock
where itemid = :itemid and date > :startdate and date < :enddate
order by date desc
这几天我没有机会接触到firebird,所以我自己也没试过
提前谢谢
问候,
雷诺第不,循环迭代总是比传统的
SELECT
语句慢
如果可以,则“”将使用索引;查看在索引中添加'itemid'是否有帮助您可能需要在日期上同时使用升序和降序索引 此外,您还可以使用“”语法:
Firebird使用索引(如果适用于>,=,
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
select first 1 lastcost from stock
where itemid = :itemid and date between :startdate and :enddate
order by date desc
SQL> show table stock2;
ITEMID INTEGER Not Null
STOCKDATE TIMESTAMP Not Null
LASTCOST DOUBLE PRECISION Nullable
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
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>
create index idx_stock2id on stock2 (itemid);
create index idx_stock2iddate on stock2 (itemid, stockdate);