我有下面运行非常缓慢的 sql 查询。我查看了执行计划,它声称 Files.OrderId 上的排序是成本最高的操作 (53%)。如果我不在任何地方按 OrderId 订购,为什么会发生这种情况?在 File.OrderId 上创建索引是我最好的选择吗?
如果有人感兴趣,执行计划。
with custOrders as
(
SELECT c.firstName + ' ' + c.lastname as Customer, c.PartnerId , c.CustomerId,o.OrderId,o.CreateDate, c.IsPrimary
FROM Customers c
LEFT JOIN CustomerRelationships as cr
ON c.CustomerId = cr.PrimaryCustomerId
INNER JOIN Orders as o
ON c.customerid = o.customerid
OR (cr.secondarycustomerid IS NOT NULL AND o.customerid = cr.secondarycustomerid)
where c.createdate >= @FromDate + ' 00:00'
AND c.createdate <= @ToDate + ' 23:59'
),
temp as
(
SELECT Row_number()
OVER (
ORDER BY c.createdate DESC) AS 'row_number',
c.customerid as customerId,
c.partnerid as partnerId,
c.Customer,
c.orderid as OrderId,
c.createdate as CreateDate,
Count(f.orderid) AS FileCount,
dbo.Getparentcustomerid(c.isprimary, c.customerid) AS ParentCustomerId,
au.firstname + ' ' + au.lastname AS Admin,
'' as blank,
0 as zero
FROM custOrders c
INNER JOIN files f
ON c.orderid = f.orderid
INNER JOIN admincustomers ac
ON c.customerid = ac.customerid
INNER JOIN adminusers au
ON ac.adminuserid = au.id
INNER JOIN filestatuses s
ON f.statusid = s.statusid
WHERE ac.adminuserid IS NOT NULL
AND f.statusid NOT IN ( 5, 6 )
GROUP BY c.customerid,
c.partnerid,
c.Customer,
c.isprimary,
c.orderid,
c.createdate,
au.firstname,
au.lastname
)