EF生成的SQL Server查询优化

时间:2018-06-22 09:36:06

标签: sql sql-server query-optimization

我需要加快EF生成的SQL查询的速度。

SELECT TOP (10) 
    [Filter1].[ID1] AS [ID], 
    [Filter1].[TransactionDateTime] AS [TransactionDateTime], 
    [Filter1].[TransactionType] AS [TransactionType], 
    [Filter1].[OrganizationID] AS [OrganizationID], 
    [Filter1].[Amount] AS [Amount], 
    [Filter1].[Value] AS [Value], 
    [Filter1].[PackagingID] AS [PackagingID], 
    [Filter1].[PackagingTransaction_ID] AS [PackagingTransaction_ID]
FROM 
    (SELECT 
         [Extent1].[ID] AS [ID1], 
         [Extent1].[TransactionDateTime] AS [TransactionDateTime], 
         [Extent1].[TransactionType] AS [TransactionType], 
         [Extent1].[PackagingID] AS [PackagingID], 
         [Extent1].[OrganizationID] AS [OrganizationID], 
         [Extent1].[Amount] AS [Amount], 
         [Extent1].[Value] AS [Value], 
         [Extent1].[PackagingTransaction_ID] AS [PackagingTransaction_ID], 
         ROW_NUMBER() OVER (ORDER BY [Extent1].[TransactionDateTime] DESC, [Extent1].[ID] DESC) AS [row_number]
     FROM   
         [dbo].[LedgerTransaction] AS [Extent1]
     INNER JOIN 
         [dbo].[Organization] AS [Extent2] ON [Extent1].[OrganizationID] = [Extent2].[ID]
                                           AND [Extent2].[OrganizationTypeCode] = 2) AS [Filter1]
WHERE 
    [Filter1].[row_number] > 0
ORDER BY 
    [Filter1].[TransactionDateTime] DESC, [Filter1].[ID1] DESC

这是数据库结构:

组织

ID  int Unchecked
ExternalID  int Unchecked
OrganizationTypeCode    tinyint Unchecked
Name    nvarchar(100)   Unchecked
Address nvarchar(50)    Checked

LedgerTransaction

ID  int Unchecked
TransactionDateTime datetime    Unchecked
TransactionType tinyint Unchecked
PackagingID int Unchecked
OrganizationID  int Unchecked
Amount  int Unchecked
Value   decimal(19, 4)  Unchecked

查询:

select count(*)
from LedgerTransaction

36529499


select count(*)
from Organization

17822

我尝试了

create index test_patrik
on Organization(Id, OrganizationTypeCode)

但这并没有带来任何改善。查询大约需要34秒才能运行。

1 个答案:

答案 0 :(得分:0)

对于此查询:

SELECT TOP (10) . . .
FROM (SELECT . . . 
      FROM [dbo].[LedgerTransaction] AS [Extent1] INNER JOIN
           [dbo].[Organization] AS [Extent2]
           ON [Extent1].[OrganizationID] = [Extent2].[ID] AND
              [Extent2].[OrganizationTypeCode] = 2
     ) AS [Filter1]
WHERE [Filter1].[row_number] > 0
ORDER BY [Filter1].[TransactionDateTime] DESC, [Filter1].[ID1] DESC;

您可以删除row_number()和外部WHERE条件。 row_number()始终大于0,因此这是多余的。

您无能为力。从Organization(OrganizationTypeCode, ID)LedgerTransaction(OrganizationID)上的索引开始。

但是,外面的ORDER BY可能会花费大量时间,对此您几乎无能为力。