linq2sql呈现不必要的ORDER BY

本文关键字:ORDER BY 不必要 linq2sql | 更新日期: 2023-09-27 17:59:46

我有一个有点复杂的linq2sql查询,它不包含任何"order-by"语句,但不知何故linq2sql认为它是必要的,并插入了它。不幸的是,这个"order-by-"语句影响了性能,我不知道如何删除它…

以下是linq2sql表达式(我认为它们可能没有帮助,但无论如何…)

var lockedBy = Guid.NewGuid();
var locks = LinqDataContext.Instance.LockBranches(3, lockedBy, DateTime.Now + TimeSpan.FromMinutes(3)); // Stored procedure...
var x = LinqDataContext.Instance.Branches
.Where(branch => branch.LockedBy == lockedBy)
.Select
(
    branch => new
    {
        Branch = branch,
        Leaves = branch.Leaves
        .Select
        (
            leaf => new
            {
                Leaf = leaf,
                Estimate = leaf.Representation.Estimates
                .GroupBy(estimate=>estimate.SegmentID)
                .Sum
                (
                    estimatesBySegment => estimatesBySegment.Average
                    (
                        estimate => estimate.EstimateRequests.Average
                        (
                            estimateRequest => estimateRequest.EstimateSubmit.Value
                        )
                    )
                )
            }
        )
    }
);

它呈现为以下sql

SELECT [t0].[ID], [t0].[IndexID], [t0].[IndexNo], [t0].[Sealed], [t0].[LockedBy], [t0].[UnlockOn], [t1].[ID] AS [ID2], [t1].[BranchID], [t1].[RepresentationID], [t1].[Xml], (
    SELECT SUM([t7].[value])
    FROM (
        SELECT AVG([t6].[value]) AS [value]
        FROM (
            SELECT (
                SELECT AVG([t5].[Value])
                FROM [dbo].[EstimateRequests] AS [t4]
                LEFT OUTER JOIN [dbo].[EstimateSubmits] AS [t5] ON [t5].[EstimateRequestID] = [t4].[ID]
                WHERE [t4].[EstimateID] = [t3].[ID]
                ) AS [value], [t2].[ID], [t3].[RepresentationID], [t3].[SegmentID]
            FROM [dbo].[Representations] AS [t2], [dbo].[Estimates] AS [t3]
            ) AS [t6]
        WHERE ([t6].[ID] = [t1].[RepresentationID]) AND ([t6].[RepresentationID] = [t6].[ID])
        GROUP BY [t6].[SegmentID]
        ) AS [t7]
    ) AS [Estimate], (
    SELECT COUNT(*)
    FROM [dbo].[Leaves] AS [t8]
    WHERE [t8].[BranchID] = [t0].[ID]
    ) AS [value]
FROM [dbo].[Branches] AS [t0]
LEFT OUTER JOIN [dbo].[Leaves] AS [t1] ON [t1].[BranchID] = [t0].[ID]
WHERE [t0].[LockedBy] = @p0
ORDER BY [t0].[ID], [t1].[ID]  <-- Here's the unnecessary ORDER BY

linq2sql呈现不必要的ORDER BY

需要order by才能区分子集合Leaves。(每次您有一个子集合,都会有一个order by