我有一个如下所示的 linq 查询:(更大查询的一部分,但这说明了问题)
from guarantee in tblGuarantees
from nextExptDev in
(from gd in tblGuaranteeDevaluations
where gd.fkGuaranteeId == guarantee.pkGuaranteeId &&
gd.Date == null
orderby gd.ExpectedDate ascending
select new
{
gd.Sum,
gd.CurrencyId,
gd.ExpectedDate
}).Take(1).DefaultIfEmpty()
select new
{
guarantee.pkGuaranteeId,
nextExptDev.Sum,
nextExptDev.CurrencyId,
nextExptDev.ExpectedDate
}
它生成以下 SQL:
SELECT [t0].[pkGuaranteeId],
[t3].[Sum] AS [Sum],
[t3].[CurrencyId] AS [CurrencyId],
[t3].[ExpectedDate] AS [ExpectedDate2]
FROM [dbo].[tblGuarantee] AS [t0]
CROSS APPLY ((SELECT NULL AS [EMPTY]) AS [t1]
OUTER APPLY (SELECT TOP (1) [t2].[Sum],
[t2].[CurrencyId],
[t2].[ExpectedDate]
FROM [dbo].[tblGuaranteeDevaluation] AS [t2]
WHERE ( [t2].[fkGuaranteeId] = [t0].[pkGuaranteeId] )
AND ( [t2].[Date] IS NULL )
ORDER BY [t2].[ExpectedDate]) AS [t3])
ORDER BY [t3].[ExpectedDate] -- Why here?
我的问题是,为什么最后一个ORDER BY
?在我更大的查询中,这确实会损害性能,我无法弄清楚为什么需要它。
此外,任何关于以更好的方式编写此内容的提示都值得赞赏。