【发布时间】:2016-07-19 08:02:33
【问题描述】:
以下 SQL 在具有 350,000 条记录的最大表 PremiseProviderBillings 的数据库上需要 5 秒。但是在有 150 万条记录的同一个数据库上,它需要一分钟多的时间
SELECT
n.CustomerInvoiceNumberId as InvoiceNo,C.CustomerBillId,c.customerid, S.Volumetric, S.Fixed, S.VAT, S.Discount, C.Debit,c.EffectiveDate,c.TransactionDateTime,s.Consumption,r.CustomerCreditNoteId--,s.Volumetric + s.Fixed + s.Vat - s.discount - c.debit as variance
FROM
CustomerPayments C
INNER JOIN
(SELECT
CustomerBillId, SUM(a.VolumetricCharge) as Volumetric,SUM(a.FixedCharge) as Fixed,
SUM(a.VAT) as VAT,SUM(a.Discount) as Discount,sum(a.EstimatedConsumption) as Consumption
FROM
PremiseProviderBillings a, PremiseProviderBills b
WHERE a.PremiseProviderBillId = b.PremiseProviderBillId
GROUP BY
CustomerBillId) S
ON
C.CustomerBillId = S.CustomerBillId
and debit <> 0 -- hide credit note lines, we mark these results with customerCreditNoteId to show they have been credited
INNER JOIN dbo.CustomerInvoiceNumbers n on c.CustomerBillId = n.CustomerBillId
left OUTER JOIN
dbo.CustomerCreditNotes AS r ON c.CustomerPaymentId = r.CustomerPaymentId
where isnull(c.transactionDateTimeEnd,'')=''
如果我随后运行内部 SQL 部分,将较小数据库上的值相加,则需要 2 秒。在更大的数据库上需要 34 秒,下面的内部 SQL...
SELECT
CustomerBillId, SUM(a.VolumetricCharge) as Volumetric,SUM(a.FixedCharge) as Fixed,
SUM(a.VAT) as VAT,SUM(a.Discount) as Discount,sum(a.EstimatedConsumption) as Consumption
FROM
PremiseProviderBillings a, PremiseProviderBills b
WHERE a.PremiseProviderBillId = b.PremiseProviderBillId
GROUP BY
CustomerBillId
因此很明显,此 SQL 根本无法扩展。鉴于数据库会增长,应该采用什么技术来改进这一点?
我已经检查了所有的连接以确保没有丢失的索引,嗯,以确保所有的连接都是基于键的并且没问题
我原以为这种方法没问题,但我应该改变 SQL 的结构吗,这是否不可扩展且效率低下?
问候
【问题讨论】:
-
PremiseProviderBillings 和 PremiseProviderBills 中的索引是什么?查询计划 + 统计 IO 输出也可以帮助解决这个问题。
-
当您的分组按某个值进行时,SQL 会尝试执行不同的操作以消除重复项...所以分组按列应该被索引或至少您应该提示 SQL 说明此列是唯一的。下一步将是总和列.. 它们是否包含在索引中作为覆盖
-
“最大的表 PremiseProviderBillings 有 350,000 条记录。但是在有 150 万条记录的同一个数据库上,它需要一分钟多的时间”,这里你不是只从这个表中获取数据。因此,根据连接输出的行数来衡量可伸缩性会更准确:“PremiseProviderBillings a, PremiseProviderBills b WHERE a.PremiseProviderBillId = b.PremiseProviderBillId”。连接输出的行数是否仍然:350K 和 1.5M?
标签: sql sql-server