我有一个客户搜索查询,当 WHERE 子句包含连接表之一的条件时,该查询的运行时间会延长 2.5 秒。该查询是从 .NET 应用程序执行的。
此查询将在 0.5 秒内运行:
SELECT DISTINCT C.customerID,C.firstName,C.lastName,C.DOB,C.SSN,C.middleName,C.email,C.phone,C.address,C.city,C.state,C.postal,C.country,C.companyID,C.scanID,C.mobile,
C.mobileProviderID,C.status,C.internalCustomerID,C.extData, (C.firstName + ' ' + C.lastName) as customerName, ISNULL(CO.companyName, '') as companyName,
ISNULL(A.accountNumber, '') as accountNumber
FROM tblCustomer AS C
LEFT JOIN tblCustomerAccount AS CA ON CA.customerID = C.customerID
LEFT JOIN tblAccount AS A ON A.accountID = CA.accountID
LEFT JOIN tblCompany AS CO ON CO.companyID=C.companyID
WHERE (C.firstname LIKE 'test%'
OR C.lastName LIKE 'test%'
OR C.email = @searchString) AND (C.status=@status OR @status=-1)
将此条件添加到 WHERE 子句中使查询在 3 秒内运行
OR A.accountNumber = 'test'
所有表都有主键索引。
我尝试过的事情:
表格统计
任何优化技巧或解释为什么运行速度较慢的解释都值得赞赏。我已经尝试了在 Google 搜索中找到的大部分内容。
添加到
WHERE
子句总是会对性能产生影响,特别是当您检查左连接表中的值时。
tblAccount
表可能有一个指向 tblCustomerAccount
表的外键。
请记住,外键不会给您连接表带来任何帮助。
如果您希望始终按
accountNumber
列进行搜索,那么最好将 tblCustomerAccount
和 tblAccount
表的左联接转换为内联接。
还为 tblAccount.accountID
和 tblAccount.accountNumber
列创建索引(尝试检查 tblAccount.accountNumber
列是否位于索引的 INCLUDE
部分中是否足够)。
也不要创建太多索引,因为这会对您的数据库产生巨大影响。