使用聚合求和函数和分组优化 sybase 查询

Optimizing sybase query with aggregate sum function and grouping

我正在尝试改进在 sybase sql 任何地方进行的 sql 查询 5.5(我知道它很旧,但这是我的任务,目前无法升级 sybase 版本)

select 
sum(pd.tax) as totaltax1,sum(pd.tax2) as totaltax2,sum(pd.tax3) as totaltax3,
sum(pd.price) as totalttc,
sum(case when pd.tax<>0 then pd.taxex else 0 end) as tax1able,
sum(case when pd.tax2<>0 then pd.taxex else 0 end) as tax2able,
sum(case when pd.tax3<>0 then pd.taxex else 0 end) as tax3able,
sum(case when pd.tax+pd.tax2+pd.tax3=0 then pd.taxex else 0 end) as nontaxable,
isnull(ra.stax1able,'') as stax1able,isnull(ra.stax1,'') as stax1,
isnull(ra.stax2able,'') as stax2able,isnull(ra.stax2,'') as stax2,
isnull(ra.stax3able,'') as stax3able,isnull(ra.stax3,'') as stax3,
isnull(ra.snontaxable,'') as snontaxable,
isnull(ra.costcenterid,0) as costcenterid,isnull(ra.depcode,0) as depcode,isnull(ra.debitcoa,'') as debitcoa
from("dba".salesheader as ph join
"dba".salesdetail as pd on ph.transact=pd.transact and ph.branchid=pd.branchid) left outer join
"dba".members as m on ph.memcode=m.id left outer join
"dba".accounting_settings as ra on ra."type"=4 and ra.branchid=1
where ph.branchid=1 and ph.opendate=20150808 and ph.amount=ph.paid and(ph.memcode=0 or m.forceexport=0)
group by ra.stax1able,ra.stax1,ra.stax2able,ra.stax2,ra.stax3able,ra.stax3,ra.snontaxable,ra.costcenterid,ra.depcode,ra.debitcoa

Table数据:

上面的查询需要 7 到 8 秒,这太长了!关于改进查询的任何提示?

P.S。所有连接列都有索引(ph.transact、pd.transact、ph.branchid、pd.branchid、ph.memcode、m.id、ra.type、ra.branchid) 此外,where 子句中的所有过滤列都有索引 (ph.opendate、ph.amount、ph.paid、m.forceexport)

我尝试过的事情:

  1. 按列为分组添加索引 (ra.stax1able, ra.stax1, ra.stax2able, ra.stax2, ra.stax3able, ra.stax3, ra.snontaxable, ra.costcenterid, ra.depcode, ra.debitcoa)
  2. 为汇总字段添加索引(pd.tax, pd.tax2, pd.tax3, pd.taxex)
  3. 使用没有 where 部分的 sql 创建视图,然后 运行 视图
  4. 正在创建一个以 opendate 和 branchid 作为参数的存储过程

None 这些更改影响了性能(仍然需要 7-8 秒)

我该怎么办?

您的 accounting_settings-table 没有与其他表连接。首先,检查一下。

要最大限度地利用索引,请确保您有索引:

  1. 对于最 I/O 限制的列(最有可能 ph.opendate, 可能 ph.branchid 取决于存在多少 branchid)
  2. 确保连接列匹配 (ph.transact, ph.branchid) 大加入

因此,尝试为 salesheader 使用复合索引(opendate、branchid、memcode),为 salesdetail 使用复合索引(transact、branchid)

好的,我已经设法将 sql 从 7-8 秒增加到 188 毫秒,仅通过在 salesheader 和 salesdetail 表之间添加一个外键。但是,我一直在网上研究这个,而且我读到外键不会提高查询性能。

Foreign keys do not directly speed up the execution of queries. They do have an indirect effect, because they guarantee that the referenced column is indexed. And the index will have an impact on performance. As you describe the problem, all the join relationships should include the primary key on one of the tables. ()

此外,我在创建外键后将其删除并重新测试查询,确实需要7-8秒。

关于为什么在我的情况下外键加速查询的任何提示?