我有一个SQL查询如下 - 很简单。
SELECT
p.ProgressClaimID,
min(p.ClaimDate) as ClaimDate,
min(p.PClaimValue) as PClaimValue,
sum(d.total) as TotalDaycost,
sum(i.amount) as TotalInvoice,
sum(round(pcd.QtyClaimed * pcd.SellRate,2)) as SellClaim
FROM
(ProgressClaim as p
LEFT JOIN
ProgressClaimDetail as pcd ON p.ProgressClaimID = pcd.ProgressClaimID)
LEFT JOIN
[DayCost] as d ON p.ProgressClaimID = d.ReportPeriod
LEFT JOIN
Invoice as i ON p.ProgressClaimID = i.ReportPeriod
WHERE
p.projectID = 4
GROUP BY
p.ProgressClaimID
但它在SQL Server 2014中运行速度非常慢(几秒钟),行数很少(最多几百个)。为了让它更奇怪,这个查询在我的相同内容上按预期运行(几乎是即时的) SQL Server CE数据库上的数据。
在SQL Server安装中,如果我取出任何连接 - 它会按预期运行剩余的3个表 - 无论哪个表被删除。
我检查了FK,索引等。似乎没有什么是明显的。任何指针都赞赏。
***编辑 执行计划http://textuploader.com/5eurg(XML)
答案 0 :(得分:0)
问题出在我的查询设计中。这是在你编写SQL一段时间后会发生的事情。本质上,查询需要很长时间,因为每个左连接都会生成后续的行的多个副本,然后将它们相加 - 第三个连接会进行大量计算。
我重写了我的查询以执行我的意思,这一切都很好。
尴尬的错误 - 这是好奇的
SELECT p.ProgressClaimID, p.ClaimDate, p.PClaimValue,
pcd.pcdTotal,
d.TotalDaycost,
i.TotalInvoice
FROM ProgressClaim as p
left join (select ProgressClaimID, sum(round(QtyClaimed * SellRate,2)) as pcdTotal from ProgressClaimDetail group by ProgressClaimID) as pcd on p.ProgressClaimID=pcd.ProgressClaimID
left join (select ReportPeriod, sum(total) as TotalDaycost from DayCost group by ReportPeriod) as d on p.ProgressClaimID= d.ReportPeriod
left join (select ReportPeriod, sum(amount) as TotalInvoice from Invoice group by ReportPeriod) as i on p.ProgressClaimID= i.ReportPeriod
where p.projectID=4