我将 ASP.NET 4.5、Entity Framework 5.0 和 LINQ 与 SQL Server 2012 一起使用。
这是一个基于网络的房地产网站应用程序。该查询从中提取数据的表大约有 200 列和大约 320 万行。
当我使用 EF 获取一些数据时,它会生成以下查询:
SELECT TOP (2)
[Filter1].[ListingID] AS [ListingID],
[Filter1].[Address] AS [Address],
[Filter1].[Beds] AS [Beds],
[Filter1].[BathsFull] AS [BathsFull],
[Filter1].[ListPrice] AS [ListPrice],
[Filter1].[RemarksPublic] AS [RemarksPublic],
[Filter1].[MLSBoardID] AS [MLSBoardID],
[Filter1].[PropertyTypeID] AS [PropertyTypeID],
[Filter1].[sysid] AS [sysid],
[Filter1].[ListAgentID] AS [ListAgentID],
[Filter1].[LastUpdateDate] AS [LastUpdateDate],
[Filter1].[ShowAddressOnlineYN] AS [ShowAddressOnlineYN],
[Filter1].[City] AS [City],
[Filter1].[State] AS [State],
[Filter1].[ZipCode] AS [ZipCode],
[Filter1].[MLSNumber] AS [MLSNumber],
[Filter1].[County] AS [County],
[Filter1].[LeasePrice] AS [LeasePrice]
FROM ( SELECT [Extent1].[ListingID] AS [ListingID], [Extent1].[MLSBoardID] AS [MLSBoardID], [Extent1].[PropertyTypeID] AS [PropertyTypeID], [Extent1].[sysid] AS [sysid], [Extent1].[Address] AS [Address], [Extent1].[BathsFull] AS [BathsFull], [Extent1].[Beds] AS [Beds], [Extent1].[City] AS [City], [Extent1].[County] AS [County], [Extent1].[LastUpdateDate] AS [LastUpdateDate], [Extent1].[LeasePrice] AS [LeasePrice], [Extent1].[ListAgentID] AS [ListAgentID], [Extent1].[ListPrice] AS [ListPrice], [Extent1].[MLSNumber] AS [MLSNumber], [Extent1].[RemarksPublic] AS [RemarksPublic], [Extent1].[ShowAddressOnlineYN] AS [ShowAddressOnlineYN], [Extent1].[State] AS [State], [Extent1].[ZipCode] AS [ZipCode], row_number() OVER (ORDER BY (Case When [Extent1].[ListAgentID] IN ('##########') Then 0 Else 1 End), ListPrice DESC, LeasePrice DESC) AS [row_number]
FROM [dbo].[Listings] AS [Extent1]
WHERE 1009 = [Extent1].[PropertyTypeID]
) AS [Filter1]
WHERE [Filter1].[row_number] > 0
ORDER BY (Case When [Filter1].[ListAgentID] IN ('##########') Then 0 Else 1 End), ListPrice DESC, LeasePrice DESC
此查询估计需要 45-50 秒来执行并返回 2 行。我可以从执行计划中看到,大部分成本都在“排序”和“排序(前 N 个排序)”中。这些占整个查询成本的 79%。
我手动将上述查询重写为:
SELECT TOP (2)
[ListingID],
[Address],
[Beds],
[BathsFull],
[ListPrice],
[RemarksPublic],
[MLSBoardID],
[PropertyTypeID],
[sysid],
[ListAgentID],
[LastUpdateDate],
[ShowAddressOnlineYN],
[City],
[State],
[ZipCode],
[MLSNumber],
[County],
[LeasePrice]
FROM dbo.Listings
WHERE 1009 = [PropertyTypeID]
ORDER BY (Case When [ListAgentID] IN ('##########') Then 0 Else 1 End), ListPrice DESC, LeasePrice DESC
我的查询返回与之前完全相同的结果,但运行时间不到 1 秒(“排序(前 N 个排序)”占成本的 91%)。两个查询在其执行计划的“索引查找”上使用相同的索引。
如何使第一个查询运行得更快?我已经尝试了各种带有索引的东西,但似乎无法让它以我编写的第二个查询的速度执行。
任何和所有的帮助表示赞赏。如果您需要更多详细信息,请告诉我。