Sqlite选择查询花时间吗?

时间:2017-01-05 17:41:00

标签: sql sqlite

我开发了一个带有sqlite数据库的pos软件。它在早期被罚款但是现在它太慢而且有很多数据存储。一些选择查看查询需要至少3分钟才能读取c#数据读取器。它是如此在数据库表结构中可能有问题。性能最差的视图如下:

首先我有股票表,存储存储表,购买接收物品表和销售凭证项目。

库存表有3000行。库存表有4600行。购买接收物品表有4500行,销售凭证物品表有130,00行。我创建了购买物品的显示总和和销售物品总和的视图=>

select

Sto.stockcode,
Sto.StockName,

IfNull((select sum(ss.OpeningQty) from StockStorages ss
where ss.stockid=Sto.stockid and ss.status='A'),0) [OpeningQty],

IfNull((select sum(pur.qty) from purchasereceiveitems pur
where pur.stockid=Sto.stockid and pur.status='A'),0) [Purqty],

IfNull((select sum(svi.qty) from salevoucheritems svi
where svi.stockid=Sto.stockid and svi.status='A'),0) [Salqty],

IfNull((select sum(sti.qty) from StockTransactionItems sti
where sti.stockid=Sto.stockid and sti.status='A'),0) [Transactionqty],

IfNull((select sum(ss.CurrentQty) from StockStorages ss
where ss.stockid=Sto.stockid and ss.status='A'),0) [CurrentQty]


from stocks Sto

where Sto.status='A'

group by Sto.StockCode

我如何改进我的结构或代码。请给我建议。

2 个答案:

答案 0 :(得分:1)

将相关子查询(O(n^2)性能)转换为左连接,如下所示:

select
    s.stockcode,
    s.stockname,
    ifnull(a.opening_qty, 0) opening_qty,
    ifnull(b.Purqty, 0) Purqty,
    ifnull(c.salqty, 0) salqty,
    ifnull(d.Transactionqty, 0) Transactionqty,
    ifnull(e.CurrentQty, 0) CurrentQty
from StockCode s
left join (select 
    stockid, 
    sum(OpeningQty) opening_qty
from StockStorages
where status='A'
group by stockid) a on s.stockid = a.stockid
left join (select 
    stockid, 
    sum(qty) Purqty
from purchasereceiveitems
where status='A'
group by stockid) b on s.stockid = b.stockid
(select 
    stockid, 
    sum(qty) salqty
from salevoucheritems
where status='A'
group by stockid) c on s.stockid = c.stockid
(select 
    stockid, 
    sum(qty) Transactionqty
from StockTransactionItems
where status='A'
group by stockid) d on s.stockid = d.stockid
(select 
    stockid, 
    sum(CurrentQty) CurrentQty
from StockStorages
where status='A'
group by stockid) e on s.stockid = e.stockid
where s.status = 'A';

答案 1 :(得分:0)

可以通过索引用于查找的列来加速此查询,以便子查询不再需要在整个表中搜索每个值:

CREATE INDEX StockStorages_ss         ON StockStorages        (stockid, status);
CREATE INDEX purchasereceiveitems_ss  ON purchasereceiveitems (stockid, status);
CREATE INDEX salevoucheritems_ss      ON salevoucheritems     (stockid, status);
CREATE INDEX StockTransactionItems_ss ON StockTransactionItems(stockid, status);
CREATE INDEX StockStorages_ss         ON StockStorages        (stockid, status);