2

工作表中有 100 万条记录。以下查询的执行时间为 30 秒。该查询并不优雅,它将返回符合条件的记录数。请帮我优化。

DECLARE @MaxIdValue varchar(100)
DECLARE @SerchFilter varchar(100) = 'test'
DECLARE @TotalRowCount int = ( SELECT 
Count(*) AS [RowCount]
FROM 
[Jobs]
INNER JOIN [Sites] ON [Jobs].[SiteId] = [Sites].[Id]  
INNER JOIN [JobStatusHistory] ON [Jobs].[JobStatusHistoryId] = [JobStatusHistory].[Id]  
INNER JOIN [JobStatuses] ON [JobStatusHistory].[StatusId] = [JobStatuses].[Id]  
INNER JOIN [JobTypes] ON [Jobs].[JobTypeId] = [JobTypes].[Id]  
LEFT JOIN [Customers] ON [Jobs].[CustomerId] = [Customers].[Id]  
LEFT JOIN [Priorities] ON [Jobs].[PriorityId] = [Priorities].[Id]  
LEFT JOIN [TaskTypes] ON [Jobs].[TaskTypeId] = [TaskTypes].[Id]  
LEFT JOIN [Areas] ON [Sites].[AreaId] = [Areas].[Id]  
WHERE
( 
 [Sites].[Active]=1
 AND 
   (
    [Jobs].[OwnedByCompanyId]=18
      OR  
    [Jobs].[OwnedByCompanyId] = 0)
      AND 
    [Jobs].[Active]=1
   ) 
 AND 
   ( 
  [Customers].[Name] LIKE '%'+@SerchFilter+'%'
 OR 
   [Sites].[Name] LIKE  '%'+@SerchFilter+'%'
   OR 
 [Sites].[Address1] LIKE  '%'+@SerchFilter+'%'
    OR 
  [Sites].[Postcode] LIKE  '%'+@SerchFilter+'%'
 OR 
  [Sites].[UPRN] LIKE  '%'+@SerchFilter+'%'
 OR 
 [Sites].[Contact] LIKE  '%'+@SerchFilter+'%'
     OR 
 [Sites].[Telephone] LIKE  '%'+@SerchFilter+'%'
   OR 
 [Sites].[Work] LIKE  '%'+@SerchFilter+'%'
 OR 
  [Sites].[MobileNumber] LIKE  '%'+@SerchFilter+'%'
  OR 
  [Areas].[Description] LIKE  '%'+@SerchFilter+'%'
    OR 
   [Jobs].[Id] LIKE  '%'+@SerchFilter+'%'
  OR 
  [Jobs].[OrderNumber] LIKE  '%'+@SerchFilter+'%'
   OR 
   [Jobs].[Description_PlainText] LIKE  '%'+@SerchFilter+'%'
  OR 
   [Jobs].[JobNumber] LIKE  '%'+@SerchFilter+'%'
  OR 
  [JobTypes].[Description] LIKE  '%'+@SerchFilter+'%'
   OR 
  [TaskTypes].[Description] LIKE  '%'+@SerchFilter+'%'
     OR 
   [Priorities].[Description] LIKE  '%'+@SerchFilter+'%'
    ) 
  )
4

3 回答 3

1

优化将是用'%'+@SerchFilter+'%'替换@SerchFilter+'%'

where 子句'%'+@SerchFilter+'%'阻止使用索引查找。

编辑:

您真的需要一次过滤所有这些字段吗?如果它不是一个数字,为​​什么还要费心在该Telephone领域搜索。

如果您使用的是 SQL Server 2005 或更高版本,您可以考虑使用FullText-Search

于 2012-08-15T11:40:15.953 回答
1

您可能想要使用更多索引和全文目录。

如果您使用的是 MS SQL 2008,您可以检查执行计划中是否缺少索引。同样从这里你可以看到为什么它需要这么长时间。

于 2012-08-15T11:54:20.877 回答
1

假设您的连接列已被适当索引,我怀疑问题出在众多 LIKE 上。不幸的是,这些都是相当昂贵的数据库操作。

做了类似的事情后,我相信您可以通过执行以下操作来获得更好的性能:

SELECT COUNT(*) FROM ... WHERE COL1 + COL2 + COL3 + COL4 + COL5 LIKE '%SEARCH%'

而不是:

SELECT COUNT(*) FROM ... WHERE 
COL1 LIKE '%SEARCH%' 
OR COL2 LIKE '%SEARCH%'
OR COL3 LIKE '%SEARCH%'
OR COL4 LIKE '%SEARCH%'
OR COL5 LIKE '%SEARCH%'
于 2012-08-15T12:14:50.323 回答