我有一个查询,使用带通配符的“ like”来搜索客户端。例如:
SELECT TOP (10) [t0].[CLIENTNUMBER], [t0].[FIRSTNAME], [t0].[LASTNAME], [t0].[MI], [t0].[MDOCNUMBER] FROM [dbo].[CLIENT] AS [t0] WHERE (LTRIM(RTRIM([t0].[DOCREVNO])) = '0') AND ([t0].[FIRSTNAME] LIKE '%John%') AND ([t0].[LASTNAME] LIKE '%Smith%') AND ([t0].[SSN] LIKE '%123%') AND ([t0].[CLIENTNUMBER] LIKE '%123%') AND ([t0].[MDOCNUMBER] LIKE '%123%') AND ([t0].[CLIENTINDICATOR] = 'ON')
它还可以在“ where”子句中使用较少的参数,例如:
SELECT TOP (10) [t0].[CLIENTNUMBER], [t0].[FIRSTNAME], [t0].[LASTNAME], [t0].[MI], [t0].[MDOCNUMBER] FROM [dbo].[CLIENT] AS [t0] WHERE (LTRIM(RTRIM([t0].[DOCREVNO])) = '0') AND ([t0].[FIRSTNAME] LIKE '%John%') AND ([t0].[CLIENTINDICATOR] = 'ON')
谁能说出优化这种查询性能的最佳方法是什么?也许我需要创建一个索引?该表在生产中最多可以有1000K条记录。
要LIKE在模式具有表单的位置上做很多事情'%XXX%',您需要查找SQL Server的全文本索引功能,并使用CONTAINS代替LIKE。照原样,您正在执行全表扫描,因为普通索引对搜索以通配符开头的项目没有帮助- 但全文索引会帮助您。
LIKE
'%XXX%'
CONTAINS
/* ... */ WHERE (LTRIM(RTRIM([t0].[DOCREVNO])) = '0') AND (contains([t0].[FIRSTNAME], 'John')) AND (contains([t0].[LASTNAME], 'Smith')) AND (contains([t0].[SSN], '123')) AND (contains([t0].[CLIENTNUMBER],'123')) AND (contains([t0].[MDOCNUMBER], '123')) AND ([t0].[CLIENTINDICATOR] = 'ON')